index.js 2.1 KB

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