简体   繁体   English

NSDateFormatter仅在特定时区为特定日期返回nil

[英]NSDateFormatter returns nil for specific date only in certain time zones

Given this code: 给出以下代码:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyyMMdd"];
NSArray *datesArray = @[@"20130326", @"20130327", @"20130328", @"20130329", @"20130330", @"20130331", @"20130401"];
for (NSString *dateString in datesArray) {
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSLog(@"date: %@", date);
}

This is the output in my timezone (EST): 这是我的时区(EST)的输出:

date: 2013-03-26 04:00:00 +0000
date: 2013-03-27 04:00:00 +0000
date: 2013-03-28 04:00:00 +0000
date: 2013-03-29 04:00:00 +0000
date: 2013-03-30 04:00:00 +0000
date: 2013-03-31 04:00:00 +0000
date: 2013-04-01 04:00:00 +0000

When I go to Settings -> General -> Date & Time, and set the timezone to Amman, Jordan (GMT+3), this is the output for the same code: 当我转到设置->常规->日期和时间,并将时区设置为约旦安曼(GMT + 3)时,这是相同代码的输出:

date: 2013-03-25 22:00:00 +0000
date: 2013-03-26 22:00:00 +0000
date: 2013-03-27 22:00:00 +0000
date: (null)
date: 2013-03-29 21:00:00 +0000
date: 2013-03-30 21:00:00 +0000
date: 2013-03-31 21:00:00 +0000

Why? 为什么?

I don't know for sure, but it is probably not a coincidence that the clocks change in Amman, Jordan on the 28th: http://www.evi.com/q/when_do_the_clocks_change_in_amman_jordan 我不确定,但是28日约旦安曼的时钟发生变化并不是偶然的: http//www.evi.com/q/when_do_the_clocks_change_in_amman_jordan

My suspicion is that the clocks jump from 2013-03-28 21:59:59 to 2013-03-28 23:00:00, so the time 2013-03-28 22:00:00 doesn't exist in the Amman, Jordan time zone. 我的怀疑是时钟从2013-03-28 21:59:59跳到2013-03-28 23:00:00,所以安曼不存在时间2013-03-28 22:00:00 ,约旦时区。

从1970年到现在的数年,数月甚至数天,我一直在循环运行,直到DST在安曼开始的日期, nil归还。

I think you have to specify the timezone for the dateFormatter when you set the value from string. 我认为从字符串设置值时,必须为dateFormatter指定时区。 See this question , its not exactly the same issue but it could help. 看到这个问题 ,它不是完全相同的问题,但可以提供帮助。

hope this helps 希望这可以帮助

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

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