How to get the number of days in a month in JavaScript
Getting the number of days in a month enables accurate calendar calculations, date validation, and scheduling functionality in JavaScript applications. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented month day calculations in numerous date picker and calendar components for enterprise applications. From my expertise, the most effective approach is using Date constructor with day 0 to get the last day of the previous month. This method automatically handles leap years and varying month lengths without complex conditional logic or lookup tables.
Use new Date(year, month, 0).getDate()
to get the number of days in any month.
// Get days in current month
function getDaysInMonth(year, month) {
// Month is 0-indexed (0 = January, 11 = December)
return new Date(year, month + 1, 0).getDate()
}
// Usage examples
const currentDate = new Date()
const currentYear = currentDate.getFullYear()
const currentMonth = currentDate.getMonth()
const daysThisMonth = getDaysInMonth(currentYear, currentMonth)
console.log('Days in current month:', daysThisMonth)
// Test various months
const testCases = [
{ year: 2025, month: 0, name: 'January' }, // 31 days
{ year: 2025, month: 1, name: 'February' }, // 28 days (not leap year)
{ year: 2024, month: 1, name: 'February' }, // 29 days (leap year)
{ year: 2025, month: 3, name: 'April' }, // 30 days
{ year: 2025, month: 11, name: 'December' } // 31 days
]
testCases.forEach(test => {
const days = getDaysInMonth(test.year, test.month)
console.log(`${test.name} ${test.year}: ${days} days`)
})
// Alternative: get days using 1-indexed month
function getDaysInMonthAlt(year, month1Based) {
return new Date(year, month1Based, 0).getDate()
}
// Usage with 1-based month (1 = January, 12 = December)
const februaryDays = getDaysInMonthAlt(2024, 2) // February 2024
console.log('February 2024 days:', februaryDays) // 29 (leap year)
// Calendar helper function
function getMonthInfo(year, month) {
const daysInMonth = getDaysInMonth(year, month)
const firstDay = new Date(year, month, 1)
const lastDay = new Date(year, month, daysInMonth)
return {
year,
month,
daysInMonth,
firstDayOfWeek: firstDay.getDay(),
lastDayOfWeek: lastDay.getDay()
}
}
const monthInfo = getMonthInfo(2025, 9) // October 2025
console.log('Month info:', monthInfo)
The Date constructor with day 0 returns the last day of the previous month, effectively giving us the total days in the target month. This approach automatically handles leap years and different month lengths. The month parameter is 0-indexed where January = 0 and December = 11.
Best Practice Note:
This is the same month calculation method we use in CoreUI calendar components for accurate date handling. Remember that JavaScript months are 0-indexed, so subtract 1 when converting from user-friendly month numbers to avoid off-by-one errors in your calculations.