在我的 Playground 中,我创建了一个简单的代码示例,将本地时间转换为“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)
所有代码都工作正常,但我有一个与代码输出有关的问题。为什么打印输出显示的时间比我的本地时间早 2 小时。转换时间为 2000 年。
最佳答案
NSTimeZone.systemTimeZone
如果无法确定系统时区,将返回 GMT 时间,我猜这就是您使用 Playground 时发生的情况。您仅使用小时、分钟和秒将日期转换为字符串
dateFormat = "HH:mm:ss"
,因此 String 没有任何关于年,这就是为什么当你使用它转换回 NSDate 时它显示 2000,因为它没有正确的信息来知道它是哪一年。
关于ios - 快速时区转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34017549/