Satyam
Satyam

Reputation: 15894

iPhone - How to get time zone offset?

We have NSTimeZone class that tells more about the time zone. But I want to get only the offset of the time. For example: +05.30 is offset for Inida In other words offset of time with reference to UTC.

One problem with following code is that it crashes with 4.3 simulator and works fine with 4.2 simulator. Because 4.2 simulator is giving output with reference to GMT and 4.3 simulator with reference to IST

NSString* tzDescription = [[NSTimeZone systemTimeZone] description];
NSArray* tzArray = [tzDescription componentsSeparatedByString:@"GMT"];
NSString* gmtStr = [[tzArray objectAtIndex:1] substringToIndex:6];

I couldn't find a solution that is generic.

Upvotes: 4

Views: 3618

Answers (1)

Darshan Prajapati
Darshan Prajapati

Reputation: 843

I think you can use NSDate and NSDateFormatter class to get the time zone offset. You can do it in following way.

NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]
initWithDateFormat:@"zzz" allowNaturalLanguage:NO];
NSString *zoneOffset = [dateFormat stringFromDate:date];

So in zoneOffset now you will be having your required thing.

Upvotes: 5

Related Questions