Languages
[Edit]
EN

JavaScript - get number of days in month

3 points
Created by:
cory
1486

In this article, we would like to show you how to get the number of days in the month in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const getMonthDaysCount = (...date) => {
    const tmp = new Date(...date);
    tmp.setMonth(tmp.getMonth() + 1);
    tmp.setDate(0);
    return tmp.getDate();
};


// Usage example:

console.log(getMonthDaysCount('Mon Sep 02 2021'));  // 30
console.log(getMonthDaysCount('2021-09-02'));       // 30
console.log(getMonthDaysCount('2021-09'));          // 30
console.log(getMonthDaysCount(2021, 10));           // 30 <- Date(year, monthm, date) constructor used
console.log(getMonthDaysCount(new Date()));         // depending on current date
console.log(getMonthDaysCount(Date.now()));         // depending on current date

 

Explanation

In the above example, we use Date class constructor that applies different variants: date string, date-time string, date, and date-time components as arguments (year, month, day, hours, minutes, seconds, milliseconds). By using ...date we forward getMonthDaysCount() arguments to Date class. Months are counted from 0 to 11, days from 1 up to 31 depending on the month. Creating Date class object with 0 as the day we achieve date that indicates last day of the previous month - that trick was used to get the number of days in the month.

Related posts

Alternative titles

  1. JavaScript - check number of days in month
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - get number of days in month

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join