getting hour component from an NSDate

自古美人都是妖i 提交于 2019-12-12 05:33:23

问题


I'm trying to get the hour component from an NSDate. Here is what I do:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+1"]];
    NSDateComponents *startComponents = [calendar components:DATE_COMPONENTS fromDate:_start];
    startComponents.timeZone =  [NSTimeZone timeZoneWithName:@"GMT+1"];
    int hours = [startComponents hour];

Now before yesterday the hours value always was one hour ahead. But since yesterday the hours value was 2 hours ahead.

I know this has something to do with the NSTimezone and the DST. But I can't get my head arround it!

Can someone help me please ?


回答1:


"GMT+1" is not recognized as a time zone name, so that

[NSTimeZone timeZoneWithName:@"GMT+1"]

is nil and the local time zone is used instead, which probably switched from Wintertime (GMT+01) to Summertime (GMT+02) last weekend in your country.

Replacing "GMT+1" with "GMT+01":

[NSTimeZone timeZoneWithName:@"GMT+01"]
// or alternatively:
[NSTimeZone timeZoneForSecondsFromGMT:3600]

works and gives the expected result.

Note that it is sufficent to set the time zone of the NSCalendar. Setting the time zone of the NSDateComponents has no effect in this case.



来源:https://stackoverflow.com/questions/22765042/getting-hour-component-from-an-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!