Thursday, June 13, 2013

NSCalendar dateByAddingComponents toDate options example in Objective C (iOS).


NSCalendar dateByAddingComponents toDate options

Returns a new NSDate object representing the absolute time calculated by adding given components to a given date.

- (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts

Parameters of [NSCalendar dateByAddingComponents toDate options]
comps
The components to add to date.
date
The date to which comps are added.
opts
Options for the calculation. See “NSDateComponents wrapping behavior” for possible values. Pass 0 to specify no options.
If you specify no options (you pass 0), overflow in a unit carries into the higher units (as in typical addition).

Return Value of [NSCalendar dateByAddingComponents toDate options]
A new NSDate object representing the absolute time calculated by adding to date the calendrical components specified by comps using the options specified by opts. Returns nil if date falls outside the defined range of the receiver or if the computation cannot be performed.

Discussion of [NSCalendar dateByAddingComponents toDate options]
Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally components are added in the order specified.

The following example shows how to add 2 months and 3 days to the current date and time using an existing calendar (gregorian):

NSCalendar dateByAddingComponents toDate options example.
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:2];
[comps setDay:3];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps release];

Example of [NSCalendar dateByAddingComponents toDate options].
NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.day = 1;

NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];

NSCalendar dateByAddingComponents toDate options example.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 // now build a NSDate object for the next day
 NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
 [offsetComponents setDay:1];
 NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: [NSDate date] options:0];
 [offsetComponents release];
 [gregorian release];

End of NSCalendar dateByAddingComponents toDate options example article.