Search code examples
iosswiftnsdatenscalendar

NSCalendar.dateFromComponents returns wrong time


I'm trying to store and retrieve a specific time in my app's user defaults (since it's recurring events date has no relevance and is ignored), but I'm having this bizarre issue where the hour is correct but the minutes and seconds are not

Here's 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 outputs the time, as such

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

And the date is correctly retrieved from the user defaults

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)

However, this happens when using dateFromComponents

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

I don't even understand where the 40 and 04 come from


Solution

  • You can solve your problem by setting the timezone correctly. For example :

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