dateWithTimeIntervalSince1970方法返回不同的时区

时间:2014-08-28 02:49:01

标签: ios objective-c nsdate

当我在dateWithTimeIntervalSince1970:

中放入不同的秒数时,时区会发生变化

以下是代码:

NSDateFormatter* dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:format];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]]; //Asia/shanghai +8:00
int64_t timestamp = 714880800 ;//  683258400
NSDate* date = [NSDate dateWithTimeIntervalSince1970:timestamp];
NSString *str = [dateFormat stringFromDate:date];

我第一次制作时间戳= 714880800 ,然后第二次制作 683258400 ,但结果是: 日期说明:

1992-08-27 02:00:00 +0000
1991-08-27 02:00:00 +0000

enter image description here

enter image description here

为什么时区不同?有没有我错过的东西?

1 个答案:

答案 0 :(得分:1)

NSDate对象代表单个时间点。它不包含任何时区信息。

Xcode尝试用特定的时区来表达NSDate对象,因为没有时区,时间是没有意义的。

Xcode为不同的NSDate对象使用不同的时区可能会试图告诉你"嘿,NSDate与时区无关,我只是用它来表达时间,所有"。

编辑:将其注销。

NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"] ;
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];
NSTimeInterval timestamp = 714880800 ;
NSDate* date1 = [NSDate dateWithTimeIntervalSince1970:timestamp];
NSLog(@"%@", date1) ;
NSString *str = [dateFormat stringFromDate:date1] ;
NSLog(@"%@", str) ;

你会得到:

1992-08-27 02:00:00 +0000 <<<< add by myself (GMT)
1992-08-27 10:00:00       <<<< add by myself (CCT)