Our DNA is written in Objective-C

Adding Days to an NSDate

Nagarajan asks:

I just want to get a date which is some 50 or 60 days away from current date.

How do i get??

There are two methods to achieving this. One that is quick and (potentially) dirty. And one that is always safe.

 The quick and dirty method was the first that I discovered when browsing documentation for NSDate. It involves simply adding enough seconds to a date to make the number of days you want to add.

NSDate *now = [NSDate date];
int daysToAdd = 50;  // or 60 :-)
NSDate *newDate1 = [now addTimeInterval:60*60*24*daysToAdd];
NSLog(@"Quick: %@", newDate1);

The above method has several limitations that I found in my experiements. One is that it does not take care of daylight saving time. So you are traversing a DST boundary you might end up with a result that is one hour off and worst case with a different day.

Thus I can only recommend the following method with uses NSDateComponents and a gregorian calendar to properly add the number of days.

NSDate *now = [NSDate date];
int daysToAdd = 50;  // or 60 :-)
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate2 = [gregorian dateByAddingComponents:components toDate:now options:0];
NSLog(@"Clean: %@", newDate2);

The date functions in Objective-C are extremely powerful, but at times they are difficult to understand for people who are new to the platform.

Categories: Q&A

%d bloggers like this: