setMonth.cjs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. "use strict";
  2. exports.setMonth = setMonth;
  3. var _index = require("./constructFrom.cjs");
  4. var _index2 = require("./getDaysInMonth.cjs");
  5. var _index3 = require("./toDate.cjs");
  6. /**
  7. * The {@link setMonth} function options.
  8. */
  9. /**
  10. * @name setMonth
  11. * @category Month Helpers
  12. * @summary Set the month to the given date.
  13. *
  14. * @description
  15. * Set the month to the given date.
  16. *
  17. * @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).
  18. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  19. *
  20. * @param date - The date to be changed
  21. * @param month - The month index to set (0-11)
  22. * @param options - The options
  23. *
  24. * @returns The new date with the month set
  25. *
  26. * @example
  27. * // Set February to 1 September 2014:
  28. * const result = setMonth(new Date(2014, 8, 1), 1)
  29. * //=> Sat Feb 01 2014 00:00:00
  30. */
  31. function setMonth(date, month, options) {
  32. const _date = (0, _index3.toDate)(date, options?.in);
  33. const year = _date.getFullYear();
  34. const day = _date.getDate();
  35. const midMonth = (0, _index.constructFrom)(options?.in || date, 0);
  36. midMonth.setFullYear(year, month, 15);
  37. midMonth.setHours(0, 0, 0, 0);
  38. const daysInMonth = (0, _index2.getDaysInMonth)(midMonth);
  39. // Set the earlier date, allows to wrap Jan 31 to Feb 28
  40. _date.setMonth(month, Math.min(day, daysInMonth));
  41. return _date;
  42. }