Ad

Our DNA is written in Swift
Jump

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

8 Comments »

  1. Hi Dr Touch, I need some help with this issue and I’m hoping you have the time to point me in the right direction, here goes:

    (1) I want to display today’s date in a UILabel, then with a button event, the tricky part…
    (2) display a date 7 days in the future UNLESS it’s the weekend, then it will display the following Monday.

    So basically I want to display ONLY weekdays, no weekends… it that even possible?

  2. Yes it’s possible and not very difficult. I’ll make a Q&A article answering your questions later today.

  3. “NSDate may not respond to AddTimeInterval”
    Messages without a matching method signature will be assumed to return id and accept

    This error message: Why ?????

  4. If you check the documentation you find that you misspelled the method.

  5. I’m french and i d’nt understand “misspelled”.
    What method exactly and where have i to put it ?
    Thanks very much

Trackbacks

  1. NSDate - iPhone Dev SDK Forum