Open In App

How to get the number of days in a specified month using JavaScript ?

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a month the task is to determine the number of days of that month using JavaScript. we can use the getDate() method for the calculation of number of days in a month.

JavaScript getDate() Method

This method returns the number of days in a month (from 1 to 31) for the defined date. 

Syntax:

Date.getDate();

Return value:

It returns a number, from 1 to 31, representing the day of the month.

Example 1: 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. 

Javascript




function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}
 
function GFG_Fun() {
    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));
}
GFG_Fun()


Output

Number of days in 2and month of the year 2020 is 29

Example 2: This example gets the days in the current month of the current year by passing the month (1-12) and year to the function daysInMonth. 

Javascript




function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}
 
function GFG_Fun() {
    let date = new Date();
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    console.log("Number of days in " + month
        + "th month of the year " + year
        + " is " + daysInMonth(month, year));
}
GFG_Fun()


Output

Number of days in 12th month of the year 2023 is 31

We have a complete list of Javascript Date Objects, to check those please go through this Javascript Date Object Complete reference article.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads