Here are different methods to get the number of days in specified month in JavaScript.
1. JavaScript getDate() Method
The getDate() method returns the number of days in a month (from 1 to 31) for the defined date.
Syntax
Date.getDate();Example: This example gets the days in the month (February) of the year (2020) by passing the month (1-12) and year to the function daysInMonth.
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
let date = new Date();
let month = 2;
let year = 2020;
console.log("Number of days in " + month
+ "and month of the year " + year
+ " is " + daysInMonth(month, year));
Output
Number of days in 2and month of the year 2020 is 29
2. Using Array
In this approach, we are using the array to store the month days for each month. We are using the ternary operator to build the logic, on using tat we are returning the number of days according to the month.
function daysInMonth(month, year) {
const daysInMonths = [31, (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0))
? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return daysInMonths[month - 1];
}
let month = 2;
let year = 2024;
console.log("Number of days in " + month + "th month of the year "
+ year + " is " + daysInMonth(month, year));
Output
Number of days in 2th month of the year 2024 is 29
3. Using Switch Statement
In this approach, a switch statement is used to return the number of days based on the specified month. This approach is straightforward and allows for direct mapping of month numbers to the corresponding number of days.
function daysInMonth(month, year) {
switch (month) {
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
return 31;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
return 30;
case 2: // February
return (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 29 : 28;
default:
return -1; // Invalid month
}
}
// Driver code
let month = 2;
let year = 2024;
console.log("Number of days in " + month + "th month of the year "
+ year + " is " + daysInMonth(month, year));
Output
Number of days in 2th month of the year 2024 is 29