index.js 1.3 KB

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