Sign in
Log inSign up

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!

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct