ios - 快速时区转换问题

标签 ios swift swift2 nsdate

在我的 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 年。

enter image description here

最佳答案

  1. NSTimeZone.systemTimeZone 如果无法确定系统时区,将返回 GMT 时间,我猜这就是您使用 Playground 时发生的情况。

  2. 您仅使用小时、分钟和秒将日期转换为字符串dateFormat = "HH:mm:ss",因此 String 没有任何关于年,这就是为什么当你使用它转换回 NSDate 时它显示 2000,因为它没有正确的信息来知道它是哪一年。

关于ios - 快速时区转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34017549/

相关文章:

iphone - 从iphone sdk中的Plist加载画线

ios - 如何解决使用 URL Session 获取数据的问题?

ios - 动画递增 UILabel

ios - UITableViewRowAction 的行为不可预测

ios - 在 iOS 企业程序中分发应用程序是否有任何限制?

ios - 从 NSMutableArrays 移除对象

ios - AVPlayer 不播放本地 mp4

ios - 匹配的几何效果向后动画似乎在 View 后面

ios - WKWebView Inside View 和 Inside ScrollView 失去联系 iOS 9

iphone - MPMoviePlayerController 和来电