简体   繁体   English

iPhone - 如何获得时区偏移?

[英]iPhone - How to get time zone offset?

We have NSTimeZone class that tells more about the time zone. 我们有NSTimeZone类,可以更多地了解时区。 But I want to get only the offset of the time. 但我想只得到时间的偏移。 For example: +05.30 is offset for Inida In other words offset of time with reference to UTC. 例如:+ 05.30是Inida的偏移量换句话说,参考UTC的时间偏移量。

One problem with following code is that it crashes with 4.3 simulator and works fine with 4.2 simulator. 以下代码的一个问题是它与4.3模拟器崩溃并且与4.2模拟器一起正常工作。 Because 4.2 simulator is giving output with reference to GMT and 4.3 simulator with reference to IST 因为4.2模拟器参考GMT和参考IST的4.3模拟器给出输出

NSString* tzDescription = [[NSTimeZone systemTimeZone] description];
NSArray* tzArray = [tzDescription componentsSeparatedByString:@"GMT"];
NSString* gmtStr = [[tzArray objectAtIndex:1] substringToIndex:6];

I couldn't find a solution that is generic. 我找不到通用的解决方案。

I think you can use NSDate and NSDateFormatter class to get the time zone offset. 我认为您可以使用NSDate和NSDateFormatter类来获取时区偏移量。 You can do it in following way. 你可以通过以下方式完成。

NSDate *date = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]
initWithDateFormat:@"zzz" allowNaturalLanguage:NO];
NSString *zoneOffset = [dateFormat stringFromDate:date];

So in zoneOffset now you will be having your required thing. 所以在zoneOffset中,你现在将拥有所需的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM