How to get the number of days in a month in JavaScript

Calculating the number of days in a month is essential for building calendars, date pickers, and scheduling features in web applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented this calculation in numerous date-related components over 25 years of development. From my expertise, the most elegant solution uses the Date constructor with day 0, which automatically returns the last day of the previous month. This approach handles leap years and all month variations automatically.

Use the Date constructor with day 0 to get the last day of the previous month.

const getDaysInMonth = (year, month) => new Date(year, month, 0).getDate()
const days = getDaysInMonth(2024, 2) // 29 (February 2024 is a leap year)

Here the function takes a year and month (1-12), then creates a new Date with day 0. JavaScript automatically adjusts this to the last day of the previous month, so month 2 with day 0 gives us the last day of January, which is actually the number of days in February. The getDate() method returns this day number.

Best Practice Note:

This is the same approach we use in CoreUI calendar components for accurate date calculations. Remember that JavaScript months are 0-indexed in Date constructors, so pass the actual month number (1-12) as the second parameter for this function to work correctly.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author