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
我增加了 2 天。新日期应该是“2013-05-19?。谁能告诉我我错了什么?提前谢谢。