Swift date formatting, getting the date back from

2019-09-11 12:25发布

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条回答
\"骚年 ilove
2楼-- · 2019-09-11 12:49

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.

查看更多
登录 后发表回答