Search code examples
swiftnsdate

Extract date components from a NSDate ignoring local time and time zones


NSDate() gives me good Universal Time (NOT local time) which is perfect for my purpose. I need to extract date components (Hour, Minute etc) from this NSDate but below code converts the time to local time. How can I extract the given universal date's components without altering them to local time zone:

let date = NSDate()
print(date) // Prints 2016-10-20 20:10:20 +0000 (Good Universal Time) 
let calendar = Calendar.current
let hour = calendar.component(.hour, from date as Date)
print(hour) // Prints 16 (Bad local hour)

Solution

  • You have to set the timezone on the calendar.

    let date = NSDate()
    print(date) // Prints 2016-10-20 20:10:20 +0000 (Good Universal Time)
    var calendar = Calendar.current
    calendar.timeZone = TimeZone(abbreviation: "UTC")!
    let hour = calendar.component(.hour, from: date as Date)
    print(hour) // Prints 20