HurkNburkS
HurkNburkS

Reputation: 5510

Return GMT offset of timezone including daylight saving

I am currently trying to return the offset of the timezone as a NSString. Currently I am doing this:

NSDateFormatter *df = [NSDateFormatter new];

[df setDateFormat:@"dd/MM/yyyy HH:mm"];

//Create the date assuming the given string is in GMT
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

//Create a date string in the local timezone
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *timezoneStr = [NSString stringWithFormat:@"%@", df.timeZone];

NSLog(@"date = %@", timezoneStr);

//returns 
//GMT-0500 (GMT-5) offset -18000

What I would like to do is return just:

-5

However, I would like to know if there is an easy way to access this number without parsing through the string and taking the value.

Also, as a side question, does the code above take into consideration +/- daylight saving?

Upvotes: 0

Views: 672

Answers (1)

Paulw11
Paulw11

Reputation: 114828

If you want the UTC offset in hours for the local time zone the you can use the following:

-(NSString *) UTCOffset {
    NSTimeZone *localTZ = [NSTimeZone localTimeZone];
    float offset = localTZ.secondsFromGMT/3600.0;
    return [NSString stringWithFormat:@"%g",offset];
}

The returned value will include any daylight savings offset if daylight savings is currently in effect. Specifically, when DST is in effect the local timezone is changed to a "DST equivalent" of the standard time zone. e.g. my time zone changes from "Australian Eastern Standard Time (UTC+10)" to "Australian Eastern Summer Time (UTC+11)".

Note also that some time zones have a fractional hour difference from UTC (30 minutes), so an integer value is not sufficient

Upvotes: 3

Related Questions