Get the Number of Days in a Month using JavaScript

To get the number of days in a month, you can use the getDate() method of JavaScript. The getDate() method returns the day of the month for the specified date.

Let’s first see the code:

// Function to get total No. of days in a month
function getNumberOfDays(year, month){
    let lastDayDate = new Date(year, month + 1, 0);
    let lastDay = lastDayDate.getDate();
    return lastDay;
}

const date = new Date();         // Today's date
let year = date.getFullYear();   // Get current Year
let month = date.getMonth();     // Get current Month index(starts at 0)

let daysInMonth = getNumberOfDays(year, month);

console.log(daysInMonth);
// Output: 30

let daysInJan = getNumberOfDays(2023, 0);  // Months starts at 0
console.log(daysInJan);   // 31

How does it work?

The total number of days in a month is nothing but the last day of the month. For example, the last day of January month is always 31st January. Therefore, the total number of days is always 31.

So, we basically have to get the last day’s date of the month we want to get the total days. To get that we are using the Date() constructor.

We have passed three parameters to the Date() constructor:

  1. The year of the month.
  2. The next month(month+1).
  3. The day of the month which we passed 0.

Now, you might be thinking why we are passing month + 1 and 0 to the Date() constructor. Well, that’s the main logic behind it.

If we pass the day as 1 to the Date() constructor, it returns the first day of the month. But if we pass it as 0, it considers the previous day’s date which is nothing but the last day of the previous month.

So, if we pass (month+1) and 0 to the Date() constructor, it will give us the last day’s date of the current month.

See the following example for clarification:

console.log(new Date(2023, 1, 0));   // Tue Jan 31 2023
console.log(new Date(2023, 6, 0));   // Fri Jun 30 2023
console.log(new Date(2023, 12, 0));  // Sun Dec 31 2023

Now, to extract the total number of days from a specified date we have used the getDate() method.

See the below example:

console.log(new Date(2023, 1, 0));   // Tue Jan 31 2023
console.log(new Date(2023, 1, 0).getDate()); // 31

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts