1

This is my code :

println(myStringDate)    // 2015-02-26T17:46:34.000Z
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDTHH:mm:ss.sssZ"
let myDate = dateFormatter.dateFromString(myStringDate)
println(myDate)        // nil

Why nil ? What am I doing wrong ?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Cherif
  • 5,223
  • 8
  • 33
  • 54
  • 1
    Pretty much everything. Study closely http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns – Hot Licks Feb 26 '15 at 18:32
  • A working solution was posted only one hour ago: http://stackoverflow.com/questions/28748162/how-do-i-format-json-date-string-in-xcode-with-swift. – Martin R Feb 26 '15 at 18:36
  • Actually just one thing, as explained by Christian. It worked. – Cherif Feb 26 '15 at 18:37

2 Answers2

7

Your problem is how you set the date format. Because there is a T in your string, you need to "escape" it and say, that it shouldn't affect the formatting of the date.

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

Also as you see, I've changed the sss to SSS which stands for miliseconds and also changed the year YYYY to lowercase yyyy also the same with the DD. You have to be really carefully, when to use upper and lowercase letters in your Dateformat-strings.

Check @HotLicks link in the comments which shows a great overview of the dateformat usage.

Christian
  • 22,585
  • 9
  • 80
  • 106
  • There are still some errors in the date format, compare for example http://stackoverflow.com/questions/28748162/how-do-i-format-json-date-string-in-xcode-with-swift. – Martin R Feb 26 '15 at 18:37
  • Don't forget to mention that Y is for YearOfWeek – Leo Dabus Feb 26 '15 at 18:56
  • @LeonardoSavioDabus Done. A bit more general. Thanks for your input. – Christian Feb 26 '15 at 18:58
  • @Christian Not general at all. If you use it It would look like it is working but it could result in a different date with older dates. If used with today's date it wouldn't probably be a problem. – Leo Dabus Feb 26 '15 at 19:01
  • 1
    DO NOT quote the `Z` in the format string. That is the timezone specifier. If you quote that then the date/time string will be treated as local time instead of Zulu time. That's not what you want. – rmaddy Feb 26 '15 at 19:16
1

I know that it's to late, but

dateFormatter.dateFormat = "YYYY-MM-DD'T'HH:mm:ss.sss'Z'"

should be

dateFormatter.dateFormat = "YYYY-MM-DD'T'HH:mm:ss.SSS'Z'"

because,

1)

ss - seconds
SSS - fractional second

sss != SSS

2)

  T -> 'T'; S -> 'S'

And nice tutorial

hbk
  • 10,908
  • 11
  • 91
  • 124