Add And Subtract Dates In Objective-C

Matthew Campbell, January 19, 2012

Here is the problem: your app works with dates and you would like to be able to find out what day came a week before, or is coming up in two years.  There are a few ways to do this but the easiest by far is to use your user’s calendar along with the NSDateComponents Foundation class to figure out precisely what these date relationships are.

Get Today’s Date In Objective-C

Before we go any further, let’s make sure we are on the same page and can get a reference to today’s date. Oh yeah, we’ll call that day today.

NSDate *today = [NSDate date];

What you can do is create a new NSDateComponents object and then specify the amount of time that you would like to add or subtract from your date.

NSDate *today = [NSDate date];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.week = -1;
dateComponents.day = -3;

Now to get the date for one week and three days ago I need to get a reference to my system calendar first:

NSCalendar *calendar = [NSCalendar currentCalendar];

Then I can use the NSCalendar function dateByAddingComponents:toDate:options: to get the date from a week and three days ago.

NSDate *today = [NSDate date];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

dateComponents.week = -1;
dateComponents.day = -3;
    
NSCalendar *calendar = [NSCalendar currentCalendar];
    
NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
                                                 toDate:today
                                                options:0];

To see the results of the subtraction above write out the two date objects to the log.

NSDate *today = [NSDate date];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];

dateComponents.week = -1;
dateComponents.day = -3;
    
NSCalendar *calendar = [NSCalendar currentCalendar];
    
NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
                                                 toDate:today
                                                options:0];

NSLog(@"Today is %@ and a week and three days ago it was %@", today, previousDate);

You will see something like this appear in your console screen:

Today is 2012-01-19 15:10:12 +0000 and a week and three days ago it was 2012-01-09 15:10:12 +0000

So What Do You Think?

Have you had any luck with this method of adding and subtracting dates in Objective-C?