Search code examples
iosnsdatensdateformatterdstnstimezone

iOS - Does setDefaultTimeZone handle daylight saving and timezone offset automatically?


Server currently store date in UTC and in the app user has option to select any timezone.

[NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithName:selectedTimeZone]]

This will override the local timezone. Do I still need to handle anything in NSDateFormatter ?

setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"

I think I don't need to call setTimeZone in NSDateFormatter if I override defaulttimezone.

And [NSDate date] will then return proper current date or it will be absolute time ?


Solution

  • There are a few related questions here.

    This will override the local timezone. Do I still need to handle anything in NSDateFormatter?

    You don't need to set the time zone, because if you don't, it uses the default value when the date formatter was created.

    I think I don't need to call setTimeZone in NSDateFormatter if I override defaulttimezone.

    True, but if you ever change the default time zone, you need to create a new NSDateFormatter, because it doesn't notice that the default has changed. Or you could just change the date formatter's time zone any time you would change the default.

    And [NSDate date] will then return proper current date or it will be absolute time ?

    The results of [NSDate date] are completely unaffected by the default time zone. NSDate has no time zone, so you get the same results even if you change the default.

    Does setDefaultTimeZone handle daylight saving and timezone offset automatically?

    If the time zone uses daylight saving time, then yes. Otherwise no. That seems obvious but keep in mind that zones like GMT-0500 don't have daylight saving time even though zones like America/New_York do.