Claudio Claudio - 1 year ago 76
iOS Question

datebyAddingTimeInterval not working

in some cases, I need to increment a NSDate in 1 day. For it, I'm using dateByAddingTimeInterval, but it's not working.

Here is the code:

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

I already tried addTimeInterval (deprecated, I know), but it's not working too. What is wrong?


Answer Source

[endDate dateByAddingTimeInterval:dayinseconds]; returns a value which is the new date produced by the function. Dates are immutable objects (like strings) so you cannot modify them - you can only get a new date by applying a function.

If you write this, instead, it will work:

endDate = [endDate dateByAddingTimeInterval:dayinseconds];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download