Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptHow to get the number of days in a specified month using...

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

Given a month and the task is to determine the number of days of that month using JavaScript. We can get the number of days in a month by following ways:

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.

JavaScript getFullYear() Method: This method returns the year (four digits for dates between year 1000 and 9999) of the defined date. 

Syntax:

Date.getFullYear()

Return value: It returns a number, representing the year of the defined date

JavaScript getMonth() Method: This method returns the month (from 0 to 11) for the defined date, based on to local time. 

Syntax:

Date.getMonth()

Return value: It returns a number, from 0 to 11, representing 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 6th month of the year 2023 is 30

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

RELATED ARTICLES

Most Popular

Recent Comments