?? 最近做的項(xiàng)目要海外用,與設(shè)備交互,比如定時(shí)延時(shí)任務(wù)什么的,就不能只按照國(guó)內(nèi)的時(shí)區(qū)來了,不然國(guó)外用著就炸了。
先擺上我最開始獲取時(shí)區(qū)的方式:(突然感覺很chun --?。?/h6>
-(NSString *)getTimezone
{
NSTimeZone *localZone = [NSTimeZone localTimeZone];
NSString *strZoneAbbreviation = [localZone abbreviation];
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z]" options:0 error:nil];
strZoneAbbreviation = [regularExpression stringByReplacingMatchesInString:strZoneAbbreviation options:0 range:NSMakeRange(0, strZoneAbbreviation.length) withTemplate:@""];
return strZoneAbbreviation;
}
-(NSString *)getTimezone
{
NSTimeZone *localZone = [NSTimeZone localTimeZone];
NSString *strZoneAbbreviation = [localZone abbreviation];
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"[a-zA-Z]" options:0 error:nil];
strZoneAbbreviation = [regularExpression stringByReplacingMatchesInString:strZoneAbbreviation options:0 range:NSMakeRange(0, strZoneAbbreviation.length) withTemplate:@""];
return strZoneAbbreviation;
}
上面的代碼你會(huì)獲取到這樣的字符串 : +8 這種什么的。就是與0時(shí)區(qū)的差值,我這里是用正則的方式去掉了字母。
后來國(guó)外的客戶用著一直有問題,然后我這邊自己修改了手機(jī)時(shí)區(qū)測(cè)試了下,這種方式確實(shí)是有問題了。
打印一下所有已知的時(shí)區(qū)看看。
NSArray *array=[NSTimeZone knownTimeZoneNames];
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSTimeZone *t=[[NSTimeZone alloc]initWithName:obj];
NSLog(@"- %@",t.abbreviation);
}];
你會(huì)發(fā)現(xiàn)如下的東西。

1.png

2.png
第一張圖這種,去掉字母就沒了。=-=
第二張圖,如果直接把得到的字符串轉(zhuǎn)整形也會(huì)有鍋。
所以呢,還是用最標(biāo)準(zhǔn)的方式比較靠譜了。
獲取當(dāng)前時(shí)區(qū)與0時(shí)區(qū)的間隔秒數(shù)
NSTimeZone *localZone = [NSTimeZone localTimeZone];
NSInteger seconds= [localZone secondsFromGMT];
這就避免了上面的兩個(gè)問題了。