How To Get the Number of Days in a Month in JavaScript

How To Get the Number of Days in a Month in JavaScript

To get the number of days in a month in JavaScript, we can use the getDate() method in JavaScript. Check out the details below to get more information.

Get the number of days in a month in JavaScript

Using the getDate() method in JavaScript

To get the number of days in a month in Javascript, we can use the getDate() method. It is a built-in function in JavaScript, and we easy call it with the getDate() syntax. This function will be returned the day of the month.

Syntax:

getDate()

Parameter: None.

Return value: The day of the month (1 to 31).

Code example 1: 

Firstly we use the Date() constructor to create a date from the month. Then set the days parameter to 0 to get the last day of the previous month because the month starts with 0. Finally, we use the getDate() method to return the number of days in the given month and year.

// Create the getNumberOfDays() function with getDate() method.
function getNumberOfDays(month, year) {
    return new Date(year, month, 0).getDate();
}

console.log("The Number of Days in October 2022: " + getNumberOfDays(10, 2022)); // 31
console.log("The Number of Days in February 2022: " + getNumberOfDays(2, 2022)); // 28
console.log("The Number of Days in February 2024: " + getNumberOfDays(2, 2024)); // 29

Output

The Number of Days in October 2022: 31
The Number of Days in February 2022: 28
The Number of Days in February 2024: 29

Example 2:

The getDate() function is a very powerful method used for many cases. So it is very helpful for us. 

In this example, we will use the getMonth() and getFullYear() method to get the current month and year. Let’s see the other article to get more information about the two methods here.

// Create the getNumberOfDays() function with getDate() method
function getNumberOfDays(month, year) {
    return new Date(year, month, 0).getDate();
}

// Get the number of days from current month and year 
var date = new Date()
var currentMonth = date.getMonth() + 1;
var currentYear = date.getFullYear();
console.log("The Number of Days in " + currentMonth + "/" + currentYear + " is: " + 
            getNumberOfDays(currentMonth, currentYear)); // 31

Output

The Number of Days in 1/2023 is: 31

Summary

In this tutorial, we have explained how to get the number of days in a month in JavaScript. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *