0

I'm working with some JSON data that returns a dateTime in this format: "2015-01-17T20:00Z", when I attempt to turn this into an NSDate object, I'm always left with nil. I've read through several of the tutorials and answers here on SO, Apple's NSDate / NSDateFormatter / Date Formatting docs, and pinged a few IRC channels.

Can anyone tell me what I'm doing wrong and a possible work around?

My failing code in a Swift playground:

let dateString = "2015-01-17T20:00Z"
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-ddThh:mmZ"
let d = dateStringFormatter.dateFromString(dateString)
println(d)

Output: "Optional(2015-01-17 06:00:00 +0000)"

Working code in the same Swift playground:

let dateString = "2015-01-17"
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd"
let d = dateStringFormatter.dateFromString(dateString)
println(d)

Output: "nil"

Kyle
  • 14,036
  • 11
  • 46
  • 61

1 Answers1

5

You have to format it like this "yyyy-MM-dd\'T\'HH:mmZ". You can try it also with this extension:

extension String {
    func toDateFormattedWith(format:String)-> NSDate {
        let formatter = NSDateFormatter()
        formatter.dateFormat = format
        return formatter.dateFromString(self)!
    }
}

as mentioned by rmaddy your date is UTC format so we will escape only the "T" as follow:

"2015-01-17T20:00Z".toDateFormattedWith("yyyy-MM-dd\'T\'HH:mmZ")  // "Jan 17, 2015, 6:00 PM"

If you need some reference formatting your dates you can use this one;

enter image description here

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • No need to escape the single quotes and do NOT quote the `Z`. The `Z` is the timezone specifier. It is not a literal character. – rmaddy Jan 13 '15 at 04:55
  • 2
    The `Z` format specifier indicates that the string should have a timezone value. It so happens that the date string specifies the timezone of "Z" which is "UTC". If you quote the "Z" in the format, the "Z" in the date string is ignored and the date string is treated as local time, not UTC time. – rmaddy Jan 13 '15 at 04:57
  • Many thanks to the both of you! I'm headed into the office now and will try escaping the T. I'll also check with the devs to see why the API is giving me a Z with no timezone. I'm used to usually have milliseconds and timezones returned by webservices. Thanks again! – Kyle Jan 13 '15 at 12:54
  • It looks as though I had two problems, I was using lower case `hh` for hours instead of the correct upper case `hh` as well as missing the escapes around `\'T\'` – Kyle Jan 13 '15 at 17:26
  • 1
    @Kyle The API is giving you a `Z` because that *is* the timezone. It represents UTC time. So the API is giving you a timezone. – rmaddy Jan 13 '15 at 18:15