1

对于 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 Programming Topics 以及 NSTimeZone 和 NSDate 类参考,但我很难将这些信息放在一起。我真的可以使用几行代码来展示它是如何使用的。

更新:在为此苦苦挣扎的同时,我正在使用命令行模板编写代码,以便我可以快速尝试。我刚刚在 iPhone 上尝试了我以前的代码,我得到NSDate 可能无法响应 '+dateWithString:'抱歉,如果这增加了混乱,谁知道 Apple 会改变这样一个基本类。

4

3 回答 3

4

用于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 命令行 [10593:903] 日期:1976-04-02 05:34:56 +1000

于 2009-11-17T11:08:31.327 回答
2

时区偏移取决于世界大部分地区的日期——其中使用夏令时/夏令时的那些部分。

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

于 2009-06-27T08:55:14.057 回答
-1

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

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

这将输出'-0700'

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

于 2009-06-27T08:37:14.077 回答