setMonth.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. exports.setMonth = setMonth;
  3. var _index = require("./constructFrom.js");
  4. var _index2 = require("./getDaysInMonth.js");
  5. var _index3 = require("./toDate.js");
  6. /**
  7. * @name setMonth
  8. * @category Month Helpers
  9. * @summary Set the month to the given date.
  10. *
  11. * @description
  12. * Set the month to the given date.
  13. *
  14. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  15. *
  16. * @param date - The date to be changed
  17. * @param month - The month index to set (0-11)
  18. *
  19. * @returns The new date with the month set
  20. *
  21. * @example
  22. * // Set February to 1 September 2014:
  23. * const result = setMonth(new Date(2014, 8, 1), 1)
  24. * //=> Sat Feb 01 2014 00:00:00
  25. */
  26. function setMonth(date, month) {
  27. const _date = (0, _index3.toDate)(date);
  28. const year = _date.getFullYear();
  29. const day = _date.getDate();
  30. const dateWithDesiredMonth = (0, _index.constructFrom)(date, 0);
  31. dateWithDesiredMonth.setFullYear(year, month, 15);
  32. dateWithDesiredMonth.setHours(0, 0, 0, 0);
  33. const daysInMonth = (0, _index2.getDaysInMonth)(dateWithDesiredMonth);
  34. // Set the last day of the new month
  35. // if the original date was the last day of the longer month
  36. _date.setMonth(month, Math.min(day, daysInMonth));
  37. return _date;
  38. }