-1

I'm getting a dateFormat from the server like this:

2016-09-04T17:44:44+02:00

So I wrote a dateformatter:

private static let jsonDateFormatter: NSDateFormatter = {
    let fmt = NSDateFormatter()
    fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss+SSS"
    return fmt
}()

there is still a problem because when I do jsonDateFormatter.dateFromString it returns nil so the dateFormat must be wrong.

I don't see the problem.

4
  • yyyy-MM-dd'T'HH:mm:ssZZZZZ?
    – Larme
    Sep 5, 2016 at 17:47
  • 1
    The plus sign belongs to the time zone part, replace +SSS with Z, S stands for fractional seconds which is wrong.
    – vadian
    Sep 5, 2016 at 17:48
  • Thank you Vadian :) that was the problem. Sep 5, 2016 at 17:50
  • 1
    You've already gotten the correct answer, but I have a suggestion for the future. If you create a date formatter and passing in a string to dateFromString returns nil, try calling stringFromDate and examining the result. It should help you figure out where your format string doesn't match your data.
    – Duncan C
    Sep 5, 2016 at 18:14

2 Answers 2

2

As per the Documentation given on Apple Docs here

The correct formatter for this type of Dates will be

yyyy-MM-dd'T'HH:mm:ssZZZZZ

As it is used in the give example

let RFC3339DateFormatter = NSDateFormatter()
RFC3339DateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
//RFC3339DateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)

/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.dateFromString(string)
2
  • 1
    Do not set the formatter's timezone. The date string has a timezone and the timezone should be parsed from the string.
    – rmaddy
    Sep 5, 2016 at 18:20
  • I agree that setting the time zone is not needed, but at the same time, it does not adversely affect the formatter (it will always use the timezone in the string). And the virtue of setting the timezone is that this formatter can also be used for constructing ISO8601/RFC3339 date strings from date objects, and these strings will always be represented in consistent GMT format (which can be useful if you're storing the dates in a SQLite database).
    – Rob
    Sep 5, 2016 at 19:34
0

Wrong format string, plus you should also read Apple's Q&A on parsing internet date:

private static let jsonDateFormatter: NSDateFormatter = {
    let fmt = NSDateFormatter()
    fmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    return fmt
}()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.