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’
(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.
Hope this might be helpful Edit The + should be there to show exactly as normal Abbreviation
-(NSString*)getTimeZoneStringForAbbriviation:(NSString*)abbr{
NSTimeZone *atimezone=[NSTimeZone timeZoneWithAbbreviation:abbr];
int minutes = (atimezone.secondsFromGMT / 60) % 60;
int hours = atimezone.secondsFromGMT / 3600;
NSString *aStrOffset=[NSString stringWithFormat:@"%02d:%02d",hours, minutes];
return [NSString stringWithFormat:@"GMT+%@",aStrOffset];
}
精彩评论