datebyAddingTimeInterval不起作用

时间:2012-01-24 14:35:58

标签: ios nsdate

在某些情况下,我需要在1天内增加一个NSDate。对于它,我正在使用dateByAddingTimeInterval,但它不起作用。

以下是代码:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy HH:mm"];
NSString *startDate = [NSString stringWithFormat:@"%@/2012 %@",dayString, begin];
NSString *endStringForDate = [NSString stringWithFormat:@"%@/2012 %@",dayString, end];

NSLog(@"Csantos: event starts: %@, event ends: %@", startDate, endStringForDate);

NSDate *beginDate = [dateFormat dateFromString:startDate];
NSDate *endDate = [dateFormat dateFromString:endStringForDate];

NSComparisonResult result = [beginDate compare:endDate];


if(result == NSOrderedDescending){
    NSTimeInterval dayinseconds = 24 * 60 * 60;

    [endDate dateByAddingTimeInterval:dayinseconds];
    NSLog(@"Csantos: event ends: %@", endDate);
}

结果:

2012-01-24 12:09:47.837 app[3689:207] Csantos: event starts: 19/02/2012 23:00, event ends: 19/02/2012 03:00
2012-01-24 12:09:47.837 app[3689:207] Csantos: event ends: 19/02/2012 03:00

我已经尝试过addTimeInterval(不推荐使用,我知道),但它也没有用。有什么问题?

问候!

3 个答案:

答案 0 :(得分:11)

[endDate dateByAddingTimeInterval:dayinseconds];返回一个值,该值是函数生成的新日期。日期是不可变对象(如字符串),因此您无法修改它们 - 您只能通过应用函数来获取新日期。

如果你写这个,相反,它会起作用:

endDate = [endDate dateByAddingTimeInterval:dayinseconds];

答案 1 :(得分:1)

[endDate dateByAddingTimeInterval:dayinseconds];不会更改现有对象(endDate),它会返回一个新的NSDate对象,所以

endDate = [endDate dateByAddingTimeInterval:dayinseconds];
NSLog(@"Csantos: event ends: %@", endDate);

答案 2 :(得分:0)

Swift 4 中,使用addingTimeInterval方法。

endDate = endDate.addingTimeInterval(dayinseconds)