Swift date formatting, getting the date back from server is not the same as sent to the server

纵然是瞬间 提交于 2019-12-25 09:14:37

问题


I am trying to parse a date that is sent to the server.

Now the date that is recieved from the server is "2016-05-10T22:34:00.000Z"

And here is my code to get a formatted date out of the above date string :

 let format="yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let dateFmt = NSDateFormatter()
    dateFmt.dateFormat = format
    let newreadableDate = dateFmt.dateFromString(dateString)
    print(newreadableDate!)
    dateFmt.dateFormat = "MMM dd hh:mm a"
            print("Formatted date is : \(dateFmt.stringFromDate(newreadableDate!))")

The print statement prints the following result : May 11 04:04 AM

The above result is totally wrong. I should get back the same date that I recieved from server but with different format.

But the newReadableDate variable prints the correct date : 2016-05-10 22:34:00 +0000

But after I format it, it gives me wrong date.

What is wrong in the above code ?


回答1:


Your code is fine. The output is correct. The date string you parse is in UTC time. But you log the final result in local time. You must live in a timezone that is 5.5 hours ahead of UTC.

The Z in the date string represents "Zulu" time which it UTC time. So the date formatter parses the string as a time in UTC time.

You then choose to print the resulting NSDate. By default, NSDateFormatter will generate a string from an NSDate in locale time.

May 10, 2016 at 22:34 UTC time is exactly the same time as May 11, 2016 at 04:04 am in your local (+0530) timezone.



来源:https://stackoverflow.com/questions/37145169/swift-date-formatting-getting-the-date-back-from-server-is-not-the-same-as-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!