Get Number of Days in Month Using JavaScript
Nathan
Posted on September 23, 2021
JavaScript's highly extensible getDate method can be customized to fetch the number of days in a given month.
However, the number of days in a given month can vary from year to year. So this function accepts both a year
and month
parameter, then returns the number of days in the given year and month:
const getDays = (year, month) => {
return new Date(year, month, 0).getDate();
};
Here's an example of how you could use this function:
const daysInSeptember = getDays(2021, 7); // Returns 31
You might also just want to pass in the current year, depending on your use case:
const daysInSeptember = getDays(new Date().getFullYear(), 7); // Returns 31
Conclusion
getDate()
is a very powerful method that does a lot of the heavy lifting for us, so this is actually a really simple function.
Thanks for reading!
💖 💪 🙅 🚩
Nathan
Posted on September 23, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.