Categories
JavaScript Answers

How to Determine the Number of Days in a Month with JavaScript?

Spread the love

We can use the getDate method to get the number of days in a month with JavaScript.

For instance, we can write:

const numDays = (y, m) => new Date(y, m, 0).getDate();  
console.log(numDays(2020, 2));

We call the Date constructor with the y year, m month, and day 0 to create the Date instance with the last date of the given month.

Then we call getDate to get the value of the last day of the month m — 1according to the calendar.

Therefore, the console log should log 29 since February 2020 has 29 days.

Determine the Number of Days in a Month with moment.js

Also, we can use the daysInMonth method that comes with momenbt.js to get the number of days in a month.

For instance, we can write:

const numDays = moment("2020-02", "YYYY-MM").daysInMonth()  
console.log(numDays);

to parse the year and month with the moment function into a moment object.

Then we call daysInMonth to get the number of days in the month for the given month.

So numDays is 29.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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