NSCalendar.dateFromComponents返回错误的时间

时间:2015-01-28 00:07:17

标签: ios swift nsdate nscalendar

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

这是我的代码

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来自哪里

1 个答案:

答案 0 :(得分:6)

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

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