getDaysInMonth.mjs 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { toDate } from "./toDate.mjs";
  2. import { constructFrom } from "./constructFrom.mjs";
  3. /**
  4. * @name getDaysInMonth
  5. * @category Month Helpers
  6. * @summary Get the number of days in a month of the given date.
  7. *
  8. * @description
  9. * Get the number of days in a month of the given date.
  10. *
  11. * @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).
  12. *
  13. * @param date - The given date
  14. *
  15. * @returns The number of days in a month
  16. *
  17. * @example
  18. * // How many days are in February 2000?
  19. * const result = getDaysInMonth(new Date(2000, 1))
  20. * //=> 29
  21. */
  22. export function getDaysInMonth(date) {
  23. const _date = toDate(date);
  24. const year = _date.getFullYear();
  25. const monthIndex = _date.getMonth();
  26. const lastDayOfMonth = constructFrom(date, 0);
  27. lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);
  28. lastDayOfMonth.setHours(0, 0, 0, 0);
  29. return lastDayOfMonth.getDate();
  30. }
  31. // Fallback for modularized imports:
  32. export default getDaysInMonth;