Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

41 строка
1.6 KiB

  1. import toInteger from '../_lib/toInteger/index.js';
  2. import toDate from '../toDate/index.js';
  3. import getDaysInMonth from '../getDaysInMonth/index.js';
  4. import requiredArgs from '../_lib/requiredArgs/index.js';
  5. /**
  6. * @name addMonths
  7. * @category Month Helpers
  8. * @summary Add the specified number of months to the given date.
  9. *
  10. * @description
  11. * Add the specified number of months to the given date.
  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} date - the date to be changed
  18. * @param {Number} amount - the amount of months to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
  19. * @returns {Date} the new date with the months added
  20. * @throws {TypeError} 2 arguments required
  21. *
  22. * @example
  23. * // Add 5 months to 1 September 2014:
  24. * var result = addMonths(new Date(2014, 8, 1), 5)
  25. * //=> Sun Feb 01 2015 00:00:00
  26. */
  27. export default function addMonths(dirtyDate, dirtyAmount) {
  28. requiredArgs(2, arguments);
  29. var date = toDate(dirtyDate);
  30. var amount = toInteger(dirtyAmount);
  31. var desiredMonth = date.getMonth() + amount;
  32. var dateWithDesiredMonth = new Date(0);
  33. dateWithDesiredMonth.setFullYear(date.getFullYear(), desiredMonth, 1);
  34. dateWithDesiredMonth.setHours(0, 0, 0, 0);
  35. var daysInMonth = getDaysInMonth(dateWithDesiredMonth); // Set the last day of the new month
  36. // if the original date was the last day of the longer month
  37. date.setMonth(desiredMonth, Math.min(daysInMonth, date.getDate()));
  38. return date;
  39. }