index.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  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. * ### v2.0.0 breaking changes:
  12. *
  13. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  14. *
  15. * @param {Date|Number} date - the given date
  16. * @returns {Number} the number of days in a month
  17. * @throws {TypeError} 1 argument required
  18. *
  19. * @example
  20. * // How many days are in February 2000?
  21. * const result = getDaysInMonth(new Date(2000, 1))
  22. * //=> 29
  23. */
  24. export default function getDaysInMonth(dirtyDate) {
  25. requiredArgs(1, arguments);
  26. var date = toDate(dirtyDate);
  27. var year = date.getFullYear();
  28. var monthIndex = date.getMonth();
  29. var lastDayOfMonth = new Date(0);
  30. lastDayOfMonth.setFullYear(year, monthIndex + 1, 0);
  31. lastDayOfMonth.setHours(0, 0, 0, 0);
  32. return lastDayOfMonth.getDate();
  33. }