NSCalendar.dateFromComponents returns 时间不对

NSCalendar.dateFromComponents returns wrong time

我正在尝试在我的应用程序的用户默认设置中存储和检索特定时间(因为它是重复发生的事件日期没有相关性并且被忽略),但是我遇到了这个奇怪的问题,时间是正确的,但是分秒不

这是我的代码

var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var flags: NSCalendarUnit = .MinuteCalendarUnit | .HourCalendarUnit | .SecondCalendarUnit
var components = calendar?.components(flags, fromDate: NSUserDefaults.standardUserDefaults().valueForKey("breakfastTime") as NSDate!)
let test = calendar?.dateFromComponents(components!) as NSDate!
NSLog("Components: %@", components!)
NSLog("Date 1: %@", NSUserDefaults.standardUserDefaults().valueForKey("breakfastTime") as NSDate)
NSLog("Date 3: %@", test!)

组件正确输出时间,因此

Components: <NSDateComponents: 0x17414a7c0>
Hour: 8
Minute: 30
Second: 0

并且从用户默认值中正确检索到日期

Date 1: 2015-01-28 07:30:00 +0000
(It's 7 rather than 8 but it makes sense, since it's stored at UTC)

但是,使用 dateFromComponents 时会发生这种情况

Date 3: 0001-01-01 07:40:04 +0000

我什至不明白40和04是从哪里来的

您可以通过正确设置时区来解决您的问题。 例如:

calendar?.timeZone = NSTimeZone(abbreviation: "GMT")!