ios - 将NSDate转为UTC字符串再转回NSDate,结果不一样

标签 ios datetime nsdate nsdateformatter utc

我想将 NSDate() 转换为 UTC 日期字符串,然后将此日期字符串转换回 NSDate,但结果不一样。

func UTCDateStringFromDate(date: NSDate) -> String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
    let dateString = dateFormatter.stringFromDate(date)
    return dateString
}
// outputs: "20150520T030303Z"
let dateString = UTCDateStringFromDate(NSDate())

func dateFromUTCDateString(dateString: String) -> NSDate {
    let dateFormatter = NSDateFormatter()
    dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss'Z'"
    return dateFormatter.dateFromString(dateString)!
}
// outputs: "May 20, 2015, 11:03 AM"
dateFromUTCDateString(dateString)

正如您看到的两个输出,当我将 NSDate() 转换为 UTC 日期字符串时,结果为“20150520T030303Z”,然后我将此日期字符串转换回 NSDate,结果为“May 20, 2015, 11:03是”。为什么时间不一样?第一个是 03:03,第二个是 11:03?

最佳答案

因为如果你只是打印一个 NSDate()

它将以 GMT 记录日期格式,因此您的时间是 UTC + 8

所以,你的代码运行得很好。

编辑:

  • NSDate 没有时区,它只是一个绝对时间的引用。

关于ios - 将NSDate转为UTC字符串再转回NSDate,结果不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339609/

相关文章:

ios - 应用商店审核流程及应用版本更新

IOS 启用指示与通知

javascript - 在 JavaScript 中将 UTC 日期转换为本地日期

python - 从 Python 中的自由文本输入中解析日期

ios - objective-C/iOS : Get date for specific day in week (sunday)

ios - 将 NSDate 转换为 NString 问题

ios - withUnsafeMutablePointer 不编译

iphone - 是什么导致了这个 iPhone 崩溃日志?

c# - 将日期转换为字符串格式 yyyy-mm-dd HH :MM:SS - C#

ios - 如何从 JSON DarkSky swift 获取一天