开发者

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];
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜