Swift 时区转换问题
Swift time zones converting issue
在我的操场上,我创建了一个简单的代码示例,将时间从我的本地区域转换为 "America/Sao_Paulo"
。
let gmtDf: NSDateFormatter = NSDateFormatter()
gmtDf.timeZone = NSTimeZone.systemTimeZone();
gmtDf.dateFormat = "HH:mm:ss"
let gmtDate: NSDate = NSDate.new()
print(gmtDate)
let estDf: NSDateFormatter = NSDateFormatter()
estDf.timeZone = NSTimeZone(name: "America/Sao_Paulo")
estDf.dateFormat = "HH:mm:ss"
let estDate: NSDate = estDf.dateFromString(gmtDf.stringFromDate(gmtDate))!
print(estDate)
所有代码都工作正常,但我有一个问题与代码 output.Why 打印输出显示时间比我当地时间早 2 小时有关。转换后的时间是2000年。
如果无法确定系统时区,NSTimeZone.systemTimeZone
将 return GMT 时间,我猜这就是这里发生的事情,因为您正在使用 Playground。
您仅使用小时、分钟和秒将日期转换为字符串dateFormat = "HH:mm:ss"
,因此字符串没有任何关于年份的信息,这就是为什么当您重新使用它转换回显示 2000 的 NSDate,因为它没有正确的信息来知道它是哪一年。
在我的操场上,我创建了一个简单的代码示例,将时间从我的本地区域转换为 "America/Sao_Paulo"
。
let gmtDf: NSDateFormatter = NSDateFormatter()
gmtDf.timeZone = NSTimeZone.systemTimeZone();
gmtDf.dateFormat = "HH:mm:ss"
let gmtDate: NSDate = NSDate.new()
print(gmtDate)
let estDf: NSDateFormatter = NSDateFormatter()
estDf.timeZone = NSTimeZone(name: "America/Sao_Paulo")
estDf.dateFormat = "HH:mm:ss"
let estDate: NSDate = estDf.dateFromString(gmtDf.stringFromDate(gmtDate))!
print(estDate)
所有代码都工作正常,但我有一个问题与代码 output.Why 打印输出显示时间比我当地时间早 2 小时有关。转换后的时间是2000年。
-
如果无法确定系统时区,
NSTimeZone.systemTimeZone
将 return GMT 时间,我猜这就是这里发生的事情,因为您正在使用 Playground。您仅使用小时、分钟和秒将日期转换为字符串
dateFormat = "HH:mm:ss"
,因此字符串没有任何关于年份的信息,这就是为什么当您重新使用它转换回显示 2000 的 NSDate,因为它没有正确的信息来知道它是哪一年。