Languages
[Edit]
EN

JavaScript - get number of days in month

0 points
Created by:
cory
286

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

 

Practical example

In this example, we create a function that:

  • creates new date object from given string in proper format (date format),
  • uses getMonth() and getFullYear() to get the month and the year respectively,
  • returns the number of days by getting number of the last day (0) of the month using getDate().
// ONLINE-RUNNER:browser;

function daysInMonth(dateString) {
  date = new Date(dateString);    // create new date object from given string
  let month = date.getMonth();    // get the month
  let year = date.getFullYear();  // get the year
  return new Date(year, month, 0).getDate();  // get number of last day in specified year & month
}

console.log(daysInMonth('Mon Sep 02 2021')); // 31

Output:

31

Related posts

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