Contents

date(byAdding:to:options:)

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

Declaration

func date(byAdding comps: DateComponents, to date: Date, options opts: NSCalendar.Options = []) -> Date?

Parameters

  • comps:

    The components to add to date.

  • date:

    The date to which comps are added.

  • opts:

    Options for the calculation. See Options for possible values.

    If you specify no options, overflow in a unit carries into the higher units (as in typical addition).

Return Value

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

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):

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];

Note that some computations can take a relatively long time.

See Also

Related Documentation

Calculating Dates