GMT + 5:30到NSTimeZoneName字符串

时间:2014-09-09 13:50:42

标签: ios objective-c nstimezone

我有一个字符串GTM + 5:30,我想要它的相关时区名称示例:Asia / Kolkata

是否有可能获得它。

NSTimeZone* localTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT+5:30"];
NSLog(@"Name: %@",localTimeZone.name);

这不会返回时区名称(亚洲/加尔各答)

如果我有格林威治标准时间+5:30

,请帮助我找到获取时区名称的方法(亚洲/加尔各答)

1 个答案:

答案 0 :(得分:1)

您可以枚举已知时区,并检查每个时区,看它是否与您想要的时区具有相同的偏移量。我的测试程序:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+5:30"];
        NSInteger secondsFromGMT = timeZone.secondsFromGMT;
        for (NSString *name in [NSTimeZone knownTimeZoneNames]) {
            NSTimeZone *candidate = [NSTimeZone timeZoneWithName:name];
            if (candidate.secondsFromGMT == secondsFromGMT) {
                NSLog(@"%@ is currently the same offset from GMT as %@", candidate.name, timeZone.name);
            }
        }
    }
    return 0;
}

输出:

2014-09-09 09:09:01.897 timezone[87091:303] Asia/Colombo is currently the same offset from GMT as GMT+0530
2014-09-09 09:09:01.898 timezone[87091:303] Asia/Kolkata is currently the same offset from GMT as GMT+0530

显然,有两个时区与GMT+5:30具有相同的偏移量。 (对于其他偏移量可以有更多其他偏移量;例如,尝试GMT-0500。)由您决定要使用哪个偏移量。