skip to Main Content

I’m converting date strings from a JSON file to Date format and most the time it works, but this example fails and I can’t figure out why. Any ideas appreciated! Thank you.

    let input = "2015-06-20T00:47:00.484Z"
    
    let dateFormatter = DateFormatter()
    dateFormatter.calendar = Calendar(identifier: .iso8601)
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    
    print("ConvertedOutput: (dateFormatter.date(from: input))")

2

Answers


  1. For milliseconds, you should use SSS instead of sss like this –

    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    
    Login or Signup to reply.
  2. Your input is a date string which corresponds to ISO8601 standard. For such date strings, the Foundation has a ISO8601DateFormatter class which helps you avoid many edge cases which can lead to wrong date parsing and that’s why it’s suggested by Apple to use for such date strings this dedicated class than using DateFormatter.

    Code with ISO8601DateFormatter

    let dateFormatterIso = ISO8601DateFormatter()
    dateFormatterIso.formatOptions = [.withFullDate, .withFullTime, .withFractionalSeconds]
    let inputDate = dateFormatterIso.date(from: input)
    

    Code with DateFormatter

    If you can’t use ISO8601DateFormatter then
    you have to correct the date format which has wrong mask for fractional seconds: .SSS instead .sss

    let dateFormatter = DateFormatter()
    dateFormatter.calendar = Calendar(identifier: .iso8601)
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    

    Both formatters returns:

    ▿ Optional<Date>
      ▿ some : 2015-06-20 00:47:00 +0000
        - timeIntervalSinceReferenceDate : 456454020.48399997
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search