2013-05-17 49 views
0
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; 

NSString *dateString = [dateFormatter stringFromDate:[NSDate date]]; 
NSLog(@"%@",dateString); 


// Retrieve NSDate instance from stringified date presentation 
NSDate *dateFromString = [dateFormatter dateFromString:dateString]; 

// Create and initialize date component instance 
NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
[dateComponents setDay:2]; 

// Retrieve date with increased days count 
NSDate *newDate = [[NSCalendar currentCalendar] 
        dateByAddingComponents:dateComponents 
        toDate:dateFromString options:0]; 

NSLog(@"Original date: %@", [dateFormatter stringFromDate:dateFromString]); 
NSLog(@"New date: %@", [dateFormatter stringFromDate:newDate]); 

輸出NSDate的錯誤輸出時添加一天的NSDate

2013-05-17 
    Original date: 2013-05-17 
    New date: 1412647-09-06 

I 2天補充。新日期應該是「2013-05-19?。誰能告訴我我錯了什麼?提前致謝。

+3

你確定'天'正確設置爲'2'嗎? - 請發佈*代碼*,而不是*屏幕截圖*。 –

+0

是的,正如Matthias所說,你從來沒有初始化你的NSDateComponents日期。你需要使用NSCalendar componentsFromDate來初始化事物。 –

+0

@HotLicks:比較[Performing Calendar Calculations]中的第一個示例(清單9)(http://developer.apple.com/library/IOS/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html)。 –

回答

1

我以爲你忘了初始化變量day如果添加

NSUInteger day = 2; 

那麼你的代碼產生在我的測試方案的預期結果

1

init方法NSDateComponents不初始化組件。因此,例如,年份是未定義的。文檔:。

An instance of NSDateComponents is not responsible for answering questions about a date beyond the 
information with which it was initialized. For example, if you initialize one with May 6, 2004, 
its weekday is NSUndefinedDateComponent 
+0

查看[Performing Calendar Calculations](http://developer.apple.com/library/IOS/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html):您只需設置組件想要添加。所以我不認爲這回答了這個問題。 –