My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Get Number of Days in Month Using JavaScript

Nathan's photo
Nathan
·Sep 23, 2021·

1 min read

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!