getDaysInMonth.js 1.0 KB

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