dateFromComponents 默认为 8:00 AM

dateFromComponents defaults to 8:00 AM

我正在尝试了解 NSCalendar 及其组件在 Swift 中的工作原理。我从日期中提取组件,更改组件属性,然后重建日期。我期待得到 Sept 9, 2015, 12:00 AM 但是 取而代之的是 Sept 9, 2015, 8:00 AM

为什么小时分量在 8:00AM?

let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
calendar?.timeZone = NSTimeZone(abbreviation: "GMT")!

let components = calendar?.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: NSDate())

components?.year            // 2016
components?.month        // 9
components?.day            // 9
components?.hour          // 4
components?.minute      // 31
components?.second      // 54

components?.year = 2015
components?.month = 9
components?.day = 9
components?.hour = 0
components?.minute = 0
components?.second = 0

calendar?.dateFromComponents(components!) // Sept 9, 2015, 8:00 AM

以上代码不适用于任何用例。我只是想了解 NSCalendarNSDateComponentsNSDate 是如何联系在一起的。

当你打印它时你会得到正确的日期,NSDate 是 Sept 9, 2015, 8:00 AM 是因为你将时区设置为 GMT,如果你将 return 日期设置为 "Sep 9, 2015, 12:00 AM"将您的时区更改为 NSTimeZone.defaultTimeZone()