Search code examples
iosswiftnscalendarnsdatecomponents

dateFromComponents defaults to 8:00 AM


I'm trying to understand how NSCalendar and its components work in Swift. I extracted components from a date, changed the components properties, and reconstructed the date. I was expecting to get Sept 9, 2015, 12:00 AM but instead got Sept 9, 2015, 8:00 AM.

Why is the hour component at 8:00AM?

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

the code above is not meant for any use-case. it's just me trying to understand how NSCalendar, NSDateComponents, and NSDate are linked together.


Solution

  • When you print it you will get the correct date, the NSDate is Sept 9, 2015, 8:00 AM is because you set the time zone to GMT, it will return date as "Sep 9, 2015, 12:00 AM" if you change your time zone to NSTimeZone.defaultTimeZone()