EN
JavaScript - get number of days in month
3
points
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.