differenceInYears.cjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. exports.differenceInYears = differenceInYears;
  3. var _index = require("./_lib/normalizeDates.cjs");
  4. var _index2 = require("./compareAsc.cjs");
  5. var _index3 = require("./differenceInCalendarYears.cjs");
  6. /**
  7. * The {@link differenceInYears} function options.
  8. */
  9. /**
  10. * @name differenceInYears
  11. * @category Year Helpers
  12. * @summary Get the number of full years between the given dates.
  13. *
  14. * @description
  15. * Get the number of full years between the given dates.
  16. *
  17. * @param laterDate - The later date
  18. * @param earlierDate - The earlier date
  19. * @param options - An object with options
  20. *
  21. * @returns The number of full years
  22. *
  23. * @example
  24. * // How many full years are between 31 December 2013 and 11 February 2015?
  25. * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))
  26. * //=> 1
  27. */
  28. function differenceInYears(laterDate, earlierDate, options) {
  29. const [laterDate_, earlierDate_] = (0, _index.normalizeDates)(
  30. options?.in,
  31. laterDate,
  32. earlierDate,
  33. );
  34. // -1 if the left date is earlier than the right date
  35. // 2023-12-31 - 2024-01-01 = -1
  36. const sign = (0, _index2.compareAsc)(laterDate_, earlierDate_);
  37. // First calculate the difference in calendar years
  38. // 2024-01-01 - 2023-12-31 = 1 year
  39. const diff = Math.abs(
  40. (0, _index3.differenceInCalendarYears)(laterDate_, earlierDate_),
  41. );
  42. // Now we need to calculate if the difference is full. To do that we set
  43. // both dates to the same year and check if the both date's month and day
  44. // form a full year.
  45. laterDate_.setFullYear(1584);
  46. earlierDate_.setFullYear(1584);
  47. // For it to be true, when the later date is indeed later than the earlier date
  48. // (2026-02-01 - 2023-12-10 = 3 years), the difference is full if
  49. // the normalized later date is also later than the normalized earlier date.
  50. // In our example, 1584-02-01 is earlier than 1584-12-10, so the difference
  51. // is partial, hence we need to subtract 1 from the difference 3 - 1 = 2.
  52. const partial = (0, _index2.compareAsc)(laterDate_, earlierDate_) === -sign;
  53. const result = sign * (diff - +partial);
  54. // Prevent negative zero
  55. return result === 0 ? 0 : result;
  56. }