2012-10-24 51 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的工作。你能證實嗎?

相關問題