index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. * @param {Date|Number} dateLeft - the later date
  14. * @param {Date|Number} dateRight - the earlier date
  15. * @returns {Number} the number of full years
  16. * @throws {TypeError} 2 arguments required
  17. *
  18. * @example
  19. * // How many full years are between 31 December 2013 and 11 February 2015?
  20. * const result = differenceInYears(new Date(2015, 1, 11), new Date(2013, 11, 31))
  21. * //=> 1
  22. */
  23. export default function differenceInYears(dirtyDateLeft, dirtyDateRight) {
  24. requiredArgs(2, arguments);
  25. var dateLeft = toDate(dirtyDateLeft);
  26. var dateRight = toDate(dirtyDateRight);
  27. var sign = compareAsc(dateLeft, dateRight);
  28. var 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. var isLastYearNotFull = compareAsc(dateLeft, dateRight) === -sign;
  36. var result = sign * (difference - Number(isLastYearNotFull));
  37. // Prevent negative zero
  38. return result === 0 ? 0 : result;
  39. }