Instance Method

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 NSCalendar.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

Calculating Dates

func date(from: DateComponents)

Returns a date representing the absolute time calculated from given components.

func date(byAdding: NSCalendar.Unit, value: Int, to: Date, options: NSCalendar.Options = [])

Returns a date representing the absolute time calculated by adding the value of a given component to a given date.

func date(bySettingUnit: NSCalendar.Unit, value: Int, of: Date, options: NSCalendar.Options = [])

Returns a new date representing the date calculated by setting a specific component of a given date to a given value, while trying to keep lower components the same.

func nextWeekendStart(AutoreleasingUnsafeMutablePointer<NSDate?>?, interval: UnsafeMutablePointer<TimeInterval>?, options: NSCalendar.Options = [], after: Date)

Returns by reference the starting date and time interval range of the next weekend period after a given date.