Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Increment an NSDate object in Objective-C

I want to take the next day by giving the current date The code i used as follows

+(NSDate *)getForDays:(int)days fromDate:(NSDate *) date {
    NSTimeInterval secondsPerDay = 24 * 60 * 60 * days;
        return [date addTimeInterval:secondsPerDay];
} 

this works fine but when the daylight saving enabled this leads to errors. How can I make this work when daylight saving is enabled.

like image 465
Hasitha Avatar asked Jul 07 '09 08:07

Hasitha


2 Answers

As you have found, what you have now is pretty error-prone. Not only can it trip up over a daylight savings change, but also what if your user has a non-gregorian calendar? Then, days are not 24 hours long.

Instead, use NSCalendar and NSDateComponents which were exactly designed for this:

+ (NSDate *)getForDays:(int)days fromDate:(NSDate *)date
{
    NSDateComponents *components= [[NSDateComponents alloc] init];
    [components setDay:days];

    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:components toDate:date options:0];
}
like image 105
4 revs, 3 users 68% Avatar answered Oct 30 '22 00:10

4 revs, 3 users 68%


Use NSCalendar to perform calculations like this. Not only is it more likely to work, but your code will be clearer.

like image 22
Peter Hosey Avatar answered Oct 30 '22 00:10

Peter Hosey