Javascript Date get last day of month

Introduction

We would like to write a function getLastDayOfMonth(year,month).

It returns the last day of month.

The returned value could be 30th, 31st or even 28/29th for February.

Parameters:

  • year - four-digits year, for instance 2012.
  • month - month, from 0 to 11.

For instance, getLastDayOfMonth(2012,1)=29 (leap year, February).



function getLastDayOfMonth(year, month) {
  let date = new Date(year, month + 1, 0);
  return date.getDate();
}

console.log( getLastDayOfMonth(2012, 0) ); // 31
console.log( getLastDayOfMonth(2012, 1) ); // 29
console.log( getLastDayOfMonth(2013, 1) ); // 28



PreviousNext

Related