将 UTC NSDate 转换为本地 NSDate 不起作用 [英] Convert UTC NSDate into Local NSDate not working

查看:44
本文介绍了将 UTC NSDate 转换为本地 NSDate 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从服务器获取的字符串 "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"我通过这种格式将此字符串转换为 NSDate.

I have a string getting from server as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z" I convert this string into NSDate by this formate.

class func convertUTCDateToLocateDate(dateStr:String) -> NSDate{
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
        dateFormatter.timeZone = NSTimeZone(name: "UTC")
        let date = dateFormatter.dateFromString(dateStr)


    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
    dateFormatter.timeZone = NSTimeZone.localTimeZone()
    let timeStamp = dateFormatter.stringFromDate(date!)
    let dateForm = NSDateFormatter()
    dateForm.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
    dateForm.timeZone = NSTimeZone.localTimeZone()
    let dateObj = dateForm.dateFromString(timeStamp)
    return dateObj!
}

假设参数字符串是2016-11-05T12:00:00.000Z"但是当我转换这个字符串并返回一个 NSDate 对象时,它不会根据我的本地时间改变时间.我在 timeStamp 字符串中得到了正确的时间(在上面的代码中).但是当我尝试将该 timeStamp 字符串转换为 NSDate 时,它​​再次显示我作为参数获得的日期和时间.

Suppose the parameter string is "2016-11-05T12:00:00.000Z" but when i convert this string and return a NSDate object it doesn't change the time according to my local time. I get my correct time in the timeStamp string (in above code). But when i try to convert that timeStamp string into NSDate it again shows that date and time which i got as a parameter.

推荐答案

您不应该更改 NSDate 的时间.NSDates 只是一个时间点,以秒计算.他们不知道时区、天、月、年、小时、分钟、秒……如果直接打印,他们将始终以 UTC 格式输出时间.
如果您更改日期以显示您所在时区的时间,您实际上是在更改 UTC 时间——因此,无论时区如何,您的日期都将代表另一个时间点.
通过不更改它们来保持它们的完整性,而是在您需要显示它们时通过日期格式化程序进行.
如果您需要进行独立于时区的时间计算,您也可以使用 NSDateComponents 代替.

You shouldnt change a NSDate's time. NSDates are just a point in time, counted by seconds. They have no clue about timezones, days, month, years, hours, minutes, seconds,… If printed directly they will always output the time in UTC.
If you change the date to show you the time of your timezone you are actually altering the time in UTC — hence your date becomes representing another point in time, no matter of the timezone.
Keep them intact by not altering them, instead when you need to display them do it via a date formatter.
If you need to do time calculations that are independent of timezones you also can work with NSDateComponents instead.

这篇关于将 UTC NSDate 转换为本地 NSDate 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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