swift - 将 NSDate 从 UTC 转换为本地给出了错误的结果

标签 swift nsdate nsdateformatter nstimezone

我正在从小时和分钟的组成部分创建一个 NSDate。它采用 GMT 格式并正确打印为:

0001-01-01 07:30:00 +0000

然后我想将其转换为我的本地时区(CET),因此我设置了 NSDateFormatter,如下所示:

formatter.timeZone = NSTimeZone.localTimeZone()

这将打印(使用.Longstyle):

08.13.00 GMT+0.43

这是错误的——应该是 GMT+1。打印 .localTimeZone() 给出正确的偏移量:

Local Time Zone (Europe/Oslo (CET) offset 3600)
<小时/>

编辑1:通过将此扩展(来自评论中链接的答案)添加到 NSDate,我可以手动偏移时区。但随后我需要将 NSDateFormatter 时区设置为 GMT,我认为这是不正确的。

extension NSDate {
  func toLocalTime() -> NSDate {    
    let timeZone = NSTimeZone.localTimeZone()
    let seconds : NSTimeInterval = Double(timeZone.secondsFromGMTForDate(self))      
    let localDate = NSDate(timeInterval: seconds, sinceDate: self)
    return localDate
  }
}
<小时/>

编辑2:我做了一个测试项目。预期输出是打印的时间与时区的偏移量相匹配。相反,它增加了 43 分钟。

func applicationDidFinishLaunching(aNotification: NSNotification) {
    let calendar = NSCalendar.currentCalendar()
    let realDateComponents = calendar.components([.Hour, .Minute], fromDate: NSDate())
    guard let realDate = calendar.dateFromComponents(realDateComponents)
        else{fatalError("Unable to get real date.")}
    let formatter = NSDateFormatter()
    formatter.timeStyle = .ShortStyle

    print(realDate)
    print(formatter.stringFromDate(realDate))
    print(NSTimeZone.localTimeZone())
}

// OUTPUT
0001-01-01 21:03:00 +0000
21.46
Local Time Zone (Europe/Oslo (CET) offset 3600)

最佳答案

NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).

显然,您正在从 .Hour.Minute 组件创建日期,这会将(不确定的)年份信息设置为 01(而不是 2001)。

大约 2000 年前的时间点是一个相当大的时间间隔,这可能会导致奇怪的行为。

关于swift - 将 NSDate 从 UTC 转换为本地给出了错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34810582/

相关文章:

objective-c - 为什么 NSDateFormatter 返回的日期相差一小时?

ios - NSString 到 NSDate 不起作用

ios - NSDateFormatter 不格式化字符串

ios - 如何在swift项目中使用TPKeyboardAvoiding?

objective-c - NSDateFormatter 从字符串返回错误的日期

ios - 我无法从 firebase 数据库获取数据作为子类对象

ios - 如何使用日期格式获取小时

objective-c - Objc,获取当前日期没有小时,分钟,秒和毫秒的最少代码行是多少?

swift - Swift 2 方向步骤循环的语法

swift - 开关盒支架