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]);
2013-05-17
Original date: 2013-05-17
New date: 1412647-09-06
I 2天補充。新日期應該是「2013-05-19?。誰能告訴我我錯了什麼?提前致謝。
你確定'天'正確設置爲'2'嗎? - 請發佈*代碼*,而不是*屏幕截圖*。 –
是的,正如Matthias所說,你從來沒有初始化你的NSDateComponents日期。你需要使用NSCalendar componentsFromDate來初始化事物。 –
@HotLicks:比較[Performing Calendar Calculations]中的第一個示例(清單9)(http://developer.apple.com/library/IOS/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html)。 –