开发者

Does NSTimeZone in iPhone adjust automatically for DST

开发者 https://www.devze.com 2023-02-28 01:27 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消