setMonth.mjs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { constructFrom } from "./constructFrom.mjs";
  2. import { getDaysInMonth } from "./getDaysInMonth.mjs";
  3. import { toDate } from "./toDate.mjs";
  4. /**
  5. * @name setMonth
  6. * @category Month Helpers
  7. * @summary Set the month to the given date.
  8. *
  9. * @description
  10. * Set the month to the given date.
  11. *
  12. * @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).
  13. *
  14. * @param date - The date to be changed
  15. * @param month - The month index to set (0-11)
  16. *
  17. * @returns The new date with the month set
  18. *
  19. * @example
  20. * // Set February to 1 September 2014:
  21. * const result = setMonth(new Date(2014, 8, 1), 1)
  22. * //=> Sat Feb 01 2014 00:00:00
  23. */
  24. export function setMonth(date, month) {
  25. const _date = toDate(date);
  26. const year = _date.getFullYear();
  27. const day = _date.getDate();
  28. const dateWithDesiredMonth = constructFrom(date, 0);
  29. dateWithDesiredMonth.setFullYear(year, month, 15);
  30. dateWithDesiredMonth.setHours(0, 0, 0, 0);
  31. const daysInMonth = getDaysInMonth(dateWithDesiredMonth);
  32. // Set the last day of the new month
  33. // if the original date was the last day of the longer month
  34. _date.setMonth(month, Math.min(day, daysInMonth));
  35. return _date;
  36. }
  37. // Fallback for modularized imports:
  38. export default setMonth;