This question already has answers here:
unexpected result of dateFromComponents:
(3个答案)
三年前关闭。
我试图了解NSCalendar及其组件如何在Swift中工作。我从日期中提取了组件,更改了组件属性,并重建了日期。我本来想得到Sept 9, 2015, 12:00 AM但是
取而代之的是Sept 9, 2015, 8:00 AM
为什么是上午8点的时间部分?
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,如果您将时区更改为"Sep 9, 2015, 12:00 AM"它将返回日期NSTimeZone.defaultTimeZone()

关于ios - dateFromComponents默认为8:00 AM ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39404063/

10-15 07:25