dateFromComponents默认为上午8:00

时间:2016-09-09 04:51:34

标签: ios swift nscalendar nsdatecomponents

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

为什么小时组件是在上午8:00?

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是如何联系在一起的。

1 个答案:

答案 0 :(得分:1)

当您打印它时,您将获得正确的日期,NSDate为Sept 9, 2015, 8:00 AM是因为您将时区设置为GMT,如果您将时区更改为{,则会将日期返回为"Sep 9, 2015, 12:00 AM" {1}}