向NSDate添加日期时NSDate输出错误

时间:2013-05-17 11:25:08

标签: iphone objective-c nsdatecomponents

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?。谁能告诉我我的错误?提前感谢。

2 个答案:

答案 0 :(得分:1)

init的{​​{1}}方法不会初始化组件。因此,例如,年份未定义。表格Apple的文档:

NSDateComponents

答案 1 :(得分:1)

我假设您忘记初始化day变量。如果你添加

NSUInteger day = 2;

然后你的代码在我的测试程序中产生预期的结果。