DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Get Number of Days in Month Using JavaScript

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();
};
Enter fullscreen mode Exit fullscreen mode

Here's an example of how you could use this function:

const daysInSeptember = getDays(2021, 7); // Returns 31
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (0)