Search code examples
iosswiftnsdatenscalendarnsdatecomponents

Creating NSDate from components without "timezone correction"


I have a function

func createDate(day: Int, month: Int, year: Int) -> NSDate {
    var comp = NSDateComponents()
    comp.day = day
    comp.month = month
    comp.year = year

    var cal = NSCalendar.currentCalendar()

    if var date = cal.dateFromComponents(comp) {
        return date
    }

    return NSDate()
}

If I call it with

createDate(07, 01, 1984)

the output is 1984-01-06 23:00:00 +0000. I assume that there is some influence from the time zone. How can I adjust my code so that the output will be 1984-01-07 00:00:00 +0000? What am I getting wrong here? How am I confused?


Solution

  • There is no need to use NSDateComponents to input time. NSCalendar already has a method for you to input your date using your local time. It is called dateWithEra. "+0000" it is not your localTime (CET) it is UTC time. Your timeZone is not stored with your NSDate object, only the corresponding UTC date and time for your localTime input.

    let myDate = NSCalendar.currentCalendar().dateWithEra(1, year: 1984, month: 1, day: 7, hour: 0, minute: 0, second: 0, nanosecond: 0)!
    
    
    myDate.descriptionWithLocale(NSLocale.currentLocale())!   // "Saturday, January 7, 1984 at 12:00:00 AM Brasilia Standard Time"
    
    
    NSTimeZone.localTimeZone().secondsFromGMT