index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import toDate from "../toDate/index.js";
  2. import differenceInCalendarYears from "../differenceInCalendarYears/index.js";
  3. import compareAsc from "../compareAsc/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. /**
  6. * @name differenceInYears
  7. * @category Year Helpers
  8. * @summary Get the number of full years between the given dates.
  9. *
  10. * @description
  11. * Get the number of full years between the given dates.
  12. *
  13. * ### v2.0.0 breaking changes:
  14. *
  15. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  16. *
  17. * @param {Date|Number} dateLeft - the later date
  18. * @param {Date|Number} dateRight - the earlier date
  19. * @returns {Number} the number of full years
  20. * @throws {TypeError} 2 arguments required
  21. *
  22. * @example
  23. * // How many full years are between 31 December 2013 and 11 February 2015?
  24. * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))
  25. * //=> 1
  26. */
  27. export default function differenceInYears(dirtyDateLeft, dirtyDateRight) {
  28. requiredArgs(2, arguments);
  29. var dateLeft = toDate(dirtyDateLeft);
  30. var dateRight = toDate(dirtyDateRight);
  31. var sign = compareAsc(dateLeft, dateRight);
  32. var difference = Math.abs(differenceInCalendarYears(dateLeft, dateRight)); // Set both dates to a valid leap year for accurate comparison when dealing
  33. // with leap days
  34. dateLeft.setFullYear(1584);
  35. dateRight.setFullYear(1584); // Math.abs(diff in full years - diff in calendar years) === 1 if last calendar year is not full
  36. // If so, result must be decreased by 1 in absolute value
  37. var isLastYearNotFull = compareAsc(dateLeft, dateRight) === -sign;
  38. var result = sign * (difference - Number(isLastYearNotFull)); // Prevent negative zero
  39. return result === 0 ? 0 : result;
  40. }