differenceInYears.mjs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { compareAsc } from "./compareAsc.mjs";
  2. import { differenceInCalendarYears } from "./differenceInCalendarYears.mjs";
  3. import { toDate } from "./toDate.mjs";
  4. /**
  5. * @name differenceInYears
  6. * @category Year Helpers
  7. * @summary Get the number of full years between the given dates.
  8. *
  9. * @description
  10. * Get the number of full years between the given dates.
  11. *
  12. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  13. *
  14. * @param dateLeft - The later date
  15. * @param dateRight - The earlier date
  16. *
  17. * @returns The number of full years
  18. *
  19. * @example
  20. * // How many full years are between 31 December 2013 and 11 February 2015?
  21. * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))
  22. * //=> 1
  23. */
  24. export function differenceInYears(dateLeft, dateRight) {
  25. const _dateLeft = toDate(dateLeft);
  26. const _dateRight = toDate(dateRight);
  27. const sign = compareAsc(_dateLeft, _dateRight);
  28. const difference = Math.abs(differenceInCalendarYears(_dateLeft, _dateRight));
  29. // Set both dates to a valid leap year for accurate comparison when dealing
  30. // with leap days
  31. _dateLeft.setFullYear(1584);
  32. _dateRight.setFullYear(1584);
  33. // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full
  34. // If so, result must be decreased by 1 in absolute value
  35. const isLastYearNotFull = compareAsc(_dateLeft, _dateRight) === -sign;
  36. const result = sign * (difference - +isLastYearNotFull);
  37. // Prevent negative zero
  38. return result === 0 ? 0 : result;
  39. }
  40. // Fallback for modularized imports:
  41. export default differenceInYears;