Steaphann
Steaphann

Reputation: 2777

getting hour component from an NSDate

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 ?

Upvotes: 0

Views: 567

Answers (1)

Martin R
Martin R

Reputation: 539765

"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.

Upvotes: 1

Related Questions