components(_:from:to:options:)
Returns the difference between two supplied dates as date components.
Declaration
func components(_ unitFlags: NSCalendar.Unit, from startingDate: Date, to resultDate: Date, options opts: NSCalendar.Options = []) -> DateComponentsParameters
- unitFlags:
Specifies the components for the returned
NSDateComponentsobject. - startingDate:
The start date for the calculation.
- resultDate:
The end date for the calculation.
- opts:
Options for the calculation. For possible values, see Options.
If you specify a “wrap” option (Wrapcomponents), the specified components are incremented and wrap around to zero/one on overflow, but do not cause higher units to be incremented. When the wrap option is not specified, overflow in a unit carries into the higher units, as in typical addition.
Return Value
An NSDateComponents object whose components are specified by unitFlags and calculated from the difference between the resultDate and startDate using the options specified by options. Returns nil if either date falls outside the defined range of the receiver or if the computation cannot be performed.
Discussion
The result is lossy if there is not a small enough unit requested to hold the full precision of the difference. Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days. The resulting component values may be negative if resultDate is before startDate.
The following example shows how to get the approximate number of months and days between two dates using an existing calendar (gregorian):
NSDate *startDate = ...;
NSDate *endDate = ...;
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
int months = [comps month];
int days = [comps day];Note that some computations can take a relatively long time.