[英]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
. 当我调用NSTimeZone的缩写方法时,它返回GMT-07:00
。 Then, when I use this value to lookup the time zone name or ( time zone identifier ) it returns nil
. 然后,当我使用此值查找时区名称或( 时区标识符 )时,它返回nil
。
I need to retrieve the official time zone identifier , eg, America/Los_Angeles
. 我需要检索官方时区标识符 ,例如America/Los_Angeles
。 Therefore, how can I convert a time zone offset abbreviation (eg, GMT-07:00
) to the official time zone identifier? 因此,如何将时区偏移缩写(例如, GMT-07:00
)转换为官方时区标识符?
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: 这是一个如何从缩写转换timeZone的示例:
NSTimeZone* localTimeZone = [NSTimeZone localTimeZone];
NSString* localAbbreviation = [localTimeZone abbreviation];
To transform it back from the localAbbreviation, is just a matter to re-create the timeZone: 要从localAbbreviation转换回来,只需要重新创建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"? 你确定缩写是“GMT-07:00”吗? Mine returns "CLT", not a GMT offset. 我的返回“CLT”,而非GMT抵消。
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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.