问题
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