How to add some time to an NSDate

Imagine you had an NSDate object and want to add days several to it. We can use NSDate method dateByAddingComponents for this, which takes – as you may have guessed – NSDateComponents as parameters.

In this example, let’s assume we want to know what date it is 5 days from today:

int daysToAdd = 5;
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc]init];
[components setDay:daysToAdd];
NSDate *futureDate = [gregorian dateByAddingComponents:components toDate:today options:0];

You can add as many and diverse components you like, such as

  • setEra:
  • setYear:
  • setMonth:
  • setDay:
  • setHour:
  • setMinute:
  • setSecond:
  • setWeek:
  • setWeekday:
  • setWeekdayOrdinal:
  • setQuarter:
  • setCalendar:
  • setTimeZone:
  • setWeekOfMonth:
  • setWeekOfYear:
  • setYearForWeekOfYear:

Check out the NSDateComponents Class Reference for more information.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.