Determine Date Based On Number Of Days In Future Or Past

Following are two methods that you can use to create an NSDate object based on a number of days in the future or past, from an existing date. For example, you can determine the date 30 days from today.

The code to determine a date in the future follows:

#define DAY_IN_SECONDS  86400
- (NSDate *)dateWithNumberOfDaysInFuture:(NSDate *)date dayCount:(NSInteger)dayCount
  // Time passed since 1/2001 to date we want
  NSTimeInterval timeInternalToFutureDate = 
    [date timeIntervalSinceReferenceDate] + (DAY_IN_SECONDS * dayCount);
  // Convert the time interval to nsdate object
  return [NSDate dateWithTimeIntervalSinceReferenceDate:timeInternalToFutureDate];

Here is how this is called, requesting a date 90 days in the future (from 4/21/2013)

  NSDate *startDate = [NSDate date];
  NSLog(@"date: %@", [self dateWithNumberOfDaysInFuture:startDate dayCount:90]);

The output is as follows:

date: 2013-07-20 21:08:35 +0000

Get Date For Number Of Days In Past

With a simple change we can get a date that is x number of days in the past. Call the method above chaning the requested dayCount to be a negative value:

- (NSDate *)dateWithNumberOfDaysInPast:(NSDate *)date dayCount:(NSInteger)dayCount
  // Use future calculation with negative value as day count
  return [self dateWithNumberOfDaysInFuture:date dayCount:(dayCount * -1)];

Here is the output when requesting the date 30 days prior to today (4/21/2013):

date: 2013-03-22 21:11:15 +0000

Both of these methods will work for any valid NSDate, not just today’s date as used in the examples.