I have a fairly simple question. I have a set of dates in UTC. I want to represent these to the user in the correct local time adjusted (or not, if DST is not currently in effect) for DST.
So, if I do something such as the following, will timeStamp be set correctly to the local time in New York taking DST into account when in effect
NSDate *date =开发者_运维知识库 initialise with a UTC time
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"America/New_York"];
[formatter setTimeZone:timeZone];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *timeStamp = [formatter stringFromDate:date];
Or so I need to do something else? Do I check NSTimeZone.isDaylightSavingTime/NSTimeZone.daylightSavingTimeOffset and adjust my date accordingly or anything like that?
Thanks in advance?
Twibbles.
Yes, NSDateFormatter
will automatically adjust for DST if you create the timeZone with [NSTimeZone timeZoneWithName]
. NSTimeZone
knows the DST rules for each time zone and can look into the future and the past and will do the right thing for the NSDate
passed to stringForDate
. However, if you create the NSTimeZone
with [NSTimeZone timeZoneForSecondsFromGMT]
DST adjustments are not made. It should also be noted that DST rules are subject to change, which means NSTimeZone
is not guaranteed to always do the right thing for all time zones.
You do not need to use NSTimeZone.isDaylightSavingTime
or NSTimeZone.daylightSavingTimeOffset
to format an NSDate
as DST correct local time. Both of those methods operate on the current time. If you want to know if an NSDate
falls within DST in a timezone you can use the NSTimeZone.isDaylightSavingTimeForDate
method and if you want to know what the DST offset is for an NSDate you can use the NSTimeZone.daylightSavingTimeOffsetForDate
method.
精彩评论