2012-10-24 52 views
1

我有一个与日期格式化程序相关的问题,它在日期“2012-10-21”返回null。NSDateFormatter根据iOS版本返回不同结果

我创建了一个示例项目只与我想要测试,只是要确保其他东西都没有结果的干扰代码。

在iOS 5中它按预期执行,但在iOS 6中日期格式化程序返回null。

这是我的代码:

NSString *myStringDate = @"2012-10-21"; 

//------------------------// 

NSLog(@"Test 1"); 

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"yyyy-MM-dd"]; 
NSDate *myDate = [formatter dateFromString:myStringDate]; 
NSLog(@"Date: %@", myDate); 

//------------------------// 

NSLog(@"Test 2"); 

NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init]; 
[formatter2 setDateFormat:@"yyyy-MM-dd"]; 
[formatter2 setTimeZone:[NSTimeZone systemTimeZone]]; 
NSDate *myDate2 = [formatter2 dateFromString:myStringDate]; 
NSLog(@"TimeZone: %@", [NSTimeZone systemTimeZone]); 
NSLog(@"Date: %@", myDate2); 

//------------------------// 

NSLog(@"Test 3"); 

NSDateFormatter *formatter3 = [[NSDateFormatter alloc] init]; 
[formatter3 setDateFormat:@"yyyy-MM-dd"]; 
[formatter3 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-7200]]; 
NSDate *myDate3 = [formatter3 dateFromString:myStringDate]; 
NSLog(@"TimeZone: %@", [NSTimeZone timeZoneForSecondsFromGMT:-7200]); 
NSLog(@"Date: %@", myDate3); 

//------------------------// 

的iOS 5.1模拟器的结果:

Test 1 
Date: 2012-10-21 03:00:00 +0000 

Test 2 
TimeZone: America/Sao_Paulo (BRST) offset -7200 (Daylight) 
Date: 2012-10-21 03:00:00 +0000 

Test 3 
TimeZone: GMT-0200 (GMT-02:00) offset -7200 
Date: 2012-10-21 02:00:00 +0000 

的iOS 6.0模拟器的结果:

Test 1 
Date: (null) 

Test 2 
TimeZone: America/Sao_Paulo (GMT-03:00) offset -7200 (Daylight) 
Date: (null) 

Test 3 
TimeZone: GMT-0200 (GMT-02:00) offset -7200 
Date: 2012-10-21 02:00:00 +0000 

NSDateFormatter在IOS 6返回null 只有当日期为"2012-10-21"。对于2012年的所有其他日期,结果在两个iOS版本上都是正确的。

任何人都可以解释为什么?它的错误?我的代码错了?

回答

1

貌似秀圣保罗有一个夏令变化对月20日/ 21日会提前一小时(http://www.timeanddate.com/worldclock/clockchange.html?n=233)。这似乎不是巧合。测试1和测试2的计算时间可能在10月21日上午12点到1点之间,这是不可能的。在这方面,iOS 6可能会更严格些。

据我所知,你的代码看起来不错,也可能是内部监督办公室的一个错误(也可能是预期的行为,而iOS 5是问题,我不能告诉!)。其他日期似乎工作的事实表明操作系统的问题,文档没有解释这是否会发生。

+0

嗨WDUK。你说的话很有道理。我测试了2011年,2013年和2014年,并且每天都会发生该错误,夏令时在我的时区开始。现在我必须检查在这种情况下要做什么来防止日期格式化程序返回nil。谢谢你的帮助。 – Rafael

+0

这听起来像是不应该发生的事情,请向Apple提交一份关于它的错误报告(尤其是如果iOS5不返回零)。 http://bugreporter.apple.com/ – WDUK

+0

好吧,我会这么做的。谢谢你的时间! – Rafael

0

这是我使用递减的时间的代码:

  • (IBAction为)showPrevDate:(ID)发送方 { 的NSString * dateForDecrement = _showDateLbl.text;

    [dateFormatter setDateFormat:@ “MMM d,YYYY(EEE)”]; [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    的NSDate * dateObjectForDecrement = [dateFormatter dateFromString:dateForDecrement];

    int subtractDays = 1;您可以使用NSDate * dateAfterDecrement = [dateObjectForDecrement dateByAddingTimeInterval :-(24 * 60 * 60 * subtractDays)]; [dateFormatter setDateFormat:@“MMM d,yyyy(EEE)”];

    _showDateLbl。text = [NSString stringWithFormat:@“%@”,[dateFormatter stringFromDate:dateAfterDecrement]];

}

不能与iOS6的工作,但与iOS5的工作。你能证实吗?

相关问题