0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Cherif
  • 5,223
  • 8
  • 33
  • 54
  • Did you set the date formatter's time zone? – mipadi Jul 13 '15 at 17:46
  • No. Actually I just want it to keep the date as is. Without time zone considerations. – Cherif Jul 13 '15 at 17:48
  • 1
    In order to format a date for output, the time zone will be taken into consideration. If the date formatter does not have a time zone set, I believe it will use the user's current time zone. You can try setting the date formatter's time zone to UTC and see if it outputs the time correctly. – mipadi Jul 13 '15 at 17:50
  • How can I get the time zone of the original date ? Then I could use it as a reference for the NSDate object. – Cherif Jul 13 '15 at 17:53
  • `NSDate` objects don't have time zones (they just represent a specific moment in time). `NSDateFormatter`s do, though. I think what's happening is that `dateString` is in UTC (indicated by the fact that it has `Z` on the end), but the date formatter is in a different time zone, so the date _appears_ to move an hour back in time when printed. – mipadi Jul 13 '15 at 18:01
  • 1
    I believe the Z in the time string indicates that the time zone is UTC. I also believe you are losing this information during the conversion by putting the single quotes around the Z character. Remove the quotes and see if it returns correct time. `YYYY-MM-dd'T'HH:mm:ss.SSSZ` – MirekE Jul 13 '15 at 18:02
  • 1
    (Also, I don't think the solution in the question this one supposedly duplicates deals very well with this particular issue. The linked question was more about printing an `NSDate` properly.) – mipadi Jul 13 '15 at 18:02
  • @MirekE it worked, you can give it as a solution. – Cherif Jul 13 '15 at 18:16

1 Answers1

1

@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)
agy
  • 2,804
  • 2
  • 15
  • 22