繁体   English   中英

在可可中,如何使用NSTimeZone以字符串形式获取系统时区偏移量?

[英]In Cocoa, how do I use NSTimeZone to get the system time zone offset as a string?

对于PDT,我想要“ -0700”。

我要确定过去的时间来确定发生了多久。

NSDate *then = [NSDate dateWithString:@"1976-04-01 12:34:56 -0700"]; // Note the hard-coded time zone at the end

我将在其他地方构造日期字符串,但是我不知道如何访问本地时区。

我阅读了有关Cocoa的Apple Dates and Times编程主题以及NSTimeZone和NSDate类参考,但是对我来说,将信息汇总在一起实在太难了。 我真的可以使用几行代码来展示其用法。

更新 :在为此苦苦挣扎的同时,我正在使用命令行模板编写代码,因此可以快速尝试。 我刚刚在iPhone上尝试了我以前的代码,但我得到NSDate可能不会响应“ + dateWithString:”很抱歉,如果这加剧了混乱,他知道苹果会改变这样的基本类。

使用NSDateFormatter从字符串构建NSDate:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];

NSDate *formatterDate;
formatterDate = [inputFormatter dateFromString:@"1976-04-01 12:34:56 -0700"];

NSString *dateString = [inputFormatter stringFromDate:formatterDate];

NSLog(@"date:%@", dateString);

这样,您可以从字符串获取本地时间,例如,字符串指定的日期:

“ 1976-04-01 12:34:56 -0700”

在时区0700 ,(我在时区GMT +1000),所以我得到:

2009-11-17 22:13:46.480 cmdline [10593:903]日期:1976-04-02 05:34:56 +1000

时区偏移量取决于世界上大多数地区的日期,其中的某些部分使用夏时制/夏令时。

唯一正确的方法是从日期和时区一起生成整个字符串。 为此使用NSDateFormatter。

最好的方法是使用简单的日历格式化程序

NSCalendarDate * date = [NSCalendarDate calendarDate];
[date setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"PDT"]];
NSLog([date descriptionWithCalendarFormat:@"%z"]);

这将输出“ -0700”

或如果您想要系统的当前时区,则省略第二行(不确定您要的是哪个时区)

暂无
暂无

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

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