Search code examples
ioscocoa-touchnsdatensdateformatter

On hour is subtracted when converting a String to NSDate


This is the code:

let dateString = "2015-07-13T17:32:32.781Z"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"
var theDate = dateFormatter.dateFromString(dateString)!
println(theDate)  // 2015-07-13 16:32:32 +0000

One hour is subtracted to the original date during the process. Why?


Solution

  • @mipadi has explained really well the problem, so I think that you should just set the time zone to UTC.

        let dateString = "2015-07-13T17:32:32.781Z"
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
        var theDate = dateFormatter.dateFromString(dateString)!
        println(theDate)