differenceBetweenDates static method

Period differenceBetweenDates(
  1. LocalDate start,
  2. LocalDate end, [
  3. PeriodUnits units = PeriodUnits.yearMonthDay
])

Returns the exact difference between two dates or returns the period between a start and an end date, using only the given units.

If end is before

  • start: Start date
  • end: End date
  • units: Units to use for calculations

Returns: The period between the given dates, using the given units.

  • ArgumentError: units contains time units, is empty or contains unknown values.
  • ArgumentError: start and end use different calendars.

Implementation

static Period differenceBetweenDates(LocalDate start, LocalDate end, [PeriodUnits units = PeriodUnits.yearMonthDay]) {
  Preconditions.checkArgument((units.value & PeriodUnits.allTimeUnits.value) == 0, 'units', "Units contains time units: $units");
  Preconditions.checkArgument(units.value != 0, 'units', "Units must not be empty");
  Preconditions.checkArgument((units.value & ~PeriodUnits.allUnits.value) == 0, 'units', "Units contains an unknown value: $units");
  CalendarSystem calendar = start.calendar;
  Preconditions.checkArgument(calendar == end.calendar, 'end', "start and end must use the same calendar system");

  if (start == end) {
    return zero;
  }

  // Optimization for single field
  var singleFieldFunction = _functionMapBetweenDates[units];
  if (singleFieldFunction != null) return singleFieldFunction(start, end);

  // Multiple fields todo: if these result_type functions are just used to make periods, we can simply them
  var result = _dateComponentsBetween(start, end, units);
  return Period(years: result.years, months: result.months, weeks: result.weeks, days: result.days);
}