NSDate如何知道它的TimeZone?

时间:2015-09-30 10:23:20

标签: ios nsdate nsdateformatter

我对这两个NSDate对象如何知道它们所处的时区感到有些困惑。我的印象是NSDate对象只存储了一个时间点而没有关于时区的信息。

我正在创建和记录两个日期:

NSString* timeString = @"6:04 PM";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"h:mm a"];
NSDate *time = [dateFormatter dateFromString:timeString];

NSDateFormatter *currentFormatter = [[NSDateFormatter alloc] init];
[currentFormatter setTimeStyle:NSDateFormatterLongStyle];
NSLog(@"%@", [currentFormatter stringFromDate:time]);
NSLog(@"%@", [currentFormatter stringFromDate:[NSDate date]]);

这会产生输出:

18:04:00 GMT
11:12:36 BST

如何知道第一个日期是GMT,第二个日期是BST?

(这是英国的夏令时。在这方面你的里程可能会有所不同)

1 个答案:

答案 0 :(得分:2)

你是对的,NSDate没有时区。您的结果并不矛盾,因为您不打印日期 - 您通过日期格式化程序打印日期信息的子集。您的currentFormatter仅返回时间信息,而不是日期信息。如果你添加这一行:

[currentFormatter setDateStyle:NSDateFormatterLongStyle];

然后结果将类似于:

January 1, 2000 at 6:04:00 PM MST
September 30, 2015 at 11:14:39 AM MDT

换句话说,它们会显示不同的时区,因为它们位于不同的日期,时区反映了该日期的效果。就我而言,它目前为MDT,但在2000年1月1日它将是MST