NSCalendar.dateFromComponents returns wrong time

I try to save and get a certain time in the default settings for my users (since the date of recurring events is not important and is ignored), but I have this strange problem when the hour is correct, but the minutes and seconds are not

Here is my code

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 correctly displays time as such

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

And the date is correctly extracted from user defaults

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

However, this happens when using dateFromComponents

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

I don’t even understand where 40 and 04 come from

+4
source share
1 answer

You can solve your problem by setting the time zone correctly. For instance:

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

All Articles