快速日期格式,从服务器取回日期与发送到服务器的日期不同 [英] Swift date formatting, getting the date back from server is not the same as sent to the server

查看:101
本文介绍了快速日期格式,从服务器取回日期与发送到服务器的日期不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析发送到服务器的日期。

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

现在从服务器接收的日期为 2016-05- 10T22:34:00.000Z

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!))")

打印语句打印以下结果: 5月11日04:04

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.

但是newReadableDate变量显示正确的日期: 2016-05-10 22 :34:00 +0000

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 ?

推荐答案

您的代码很好。输出正确。您解析的日期字符串以UTC时间表示。但是您将最终结果记录在当地时间。您必须居住在比UTC早5.5小时的时区。

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.

日期字符串中的 Z 表示祖鲁语的时间,它是UTC时间。因此,日期格式化程序将字符串解析为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.

然后您选择打印生成的 NSDate 。默认情况下, NSDateFormatter 将从本地时间中的 NSDate 生成一个字符串。

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

2016年5月10日世界标准时间与您当地的(+0530)时区与2016年5月11日上午04:04完全相同。

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.

这篇关于快速日期格式,从服务器取回日期与发送到服务器的日期不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆