index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 setMonth
  7. * @category Month Helpers
  8. * @summary Set the month to the given date.
  9. *
  10. * @description
  11. * Set the month 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} month - the month of the new date
  19. * @returns {Date} the new date with the month set
  20. * @throws {TypeError} 2 arguments required
  21. *
  22. * @example
  23. * // Set February to 1 September 2014:
  24. * const result = setMonth(new Date(2014, 8, 1), 1)
  25. * //=> Sat Feb 01 2014 00:00:00
  26. */
  27. export default function setMonth(dirtyDate, dirtyMonth) {
  28. requiredArgs(2, arguments);
  29. var date = toDate(dirtyDate);
  30. var month = toInteger(dirtyMonth);
  31. var year = date.getFullYear();
  32. var day = date.getDate();
  33. var dateWithDesiredMonth = new Date(0);
  34. dateWithDesiredMonth.setFullYear(year, month, 15);
  35. dateWithDesiredMonth.setHours(0, 0, 0, 0);
  36. var daysInMonth = getDaysInMonth(dateWithDesiredMonth); // Set the last day of the new month
  37. // if the original date was the last day of the longer month
  38. date.setMonth(month, Math.min(day, daysInMonth));
  39. return date;
  40. }