differenceInYears.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. exports.differenceInYears = differenceInYears;
  3. var _index = require("./compareAsc.js");
  4. var _index2 = require("./differenceInCalendarYears.js");
  5. var _index3 = require("./toDate.js");
  6. /**
  7. * @name differenceInYears
  8. * @category Year Helpers
  9. * @summary Get the number of full years between the given dates.
  10. *
  11. * @description
  12. * Get the number of full years between the given dates.
  13. *
  14. * @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).
  15. *
  16. * @param dateLeft - The later date
  17. * @param dateRight - The earlier date
  18. *
  19. * @returns The number of full years
  20. *
  21. * @example
  22. * // How many full years are between 31 December 2013 and 11 February 2015?
  23. * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))
  24. * //=> 1
  25. */
  26. function differenceInYears(dateLeft, dateRight) {
  27. const _dateLeft = (0, _index3.toDate)(dateLeft);
  28. const _dateRight = (0, _index3.toDate)(dateRight);
  29. const sign = (0, _index.compareAsc)(_dateLeft, _dateRight);
  30. const difference = Math.abs(
  31. (0, _index2.differenceInCalendarYears)(_dateLeft, _dateRight),
  32. );
  33. // Set both dates to a valid leap year for accurate comparison when dealing
  34. // with leap days
  35. _dateLeft.setFullYear(1584);
  36. _dateRight.setFullYear(1584);
  37. // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full
  38. // If so, result must be decreased by 1 in absolute value
  39. const isLastYearNotFull =
  40. (0, _index.compareAsc)(_dateLeft, _dateRight) === -sign;
  41. const result = sign * (difference - +isLastYearNotFull);
  42. // Prevent negative zero
  43. return result === 0 ? 0 : result;
  44. }