Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a time zone offset abbreviation to the official time zone identifier?

When I call NSTimeZone’s abbreviation method it returns GMT-07:00. Then, when I use this value to lookup the time zone name or (time zone identifier) it returns nil.

I need to retrieve the official time zone identifier, e.g., America/Los_Angeles. Therefore, how can I convert a time zone offset abbreviation (e.g., GMT-07:00) to the official time zone identifier?

Here’s my code:

NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
NSString* localAbbreviation = [localTimeZone abbreviation];
NSDictionary* abbreviationDictionary = [NSTimeZone abbreviationDictionary];
NSString* timeZoneID = 
[abbreviationDictionary objectForKey:localAbbreviation]; //should return 'America/Los_Angeles' if the abbreviation is ‘PDT’
like image 313
johnnieb Avatar asked Feb 24 '23 03:02

johnnieb


1 Answers

(I rewrote my reply, I misunderstood the question before).

Here's an example on how to convert a timeZone from the abbreviation:

NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
NSString* localAbbreviation = [localTimeZone abbreviation];

To transform it back from the localAbbreviation, is just a matter to re-create the timeZone:

NSTimeZone* timeZoneFromAbbreviation = [NStimeZone timeZoneWithAbbreviation:abbreviation];
NSString* timeZoneIdentifier = timeZoneAbbreviation.name;

NSLog(@"Identifier: %@", timeZoneIdentifier); // Outputs America/Santiago for me.

Are you sure the abbreviation is returning "GMT-07:00"? Mine returns "CLT", not a GMT offset.

like image 179
Can Avatar answered Feb 25 '23 16:02

Can