The last day of the month is 28, 29, 30, or 31, depending upon the month and year.
The simplest way to check if a date is the last day of the month is by adding 1 to the date and then checking the value of the date. If the date becomes 1, then the given date is the last day of the month; otherwise, it is not.
let d1 = new Date('2020-02-29'); d1.setDate(d1.getDate() + 1); if(d1.getDate() === 1){ console.log('Date d1 is the last day of the month.'); }else{ console.log('Date d1 is not the last day of the month.'); } let d2 = new Date('2022-03-30'); d2.setDate(d1.getDate() + 1); if(d2.getDate() === 1){ console.log('Date d2 is the last day of the month.'); }else{ console.log('Date d2 is not the last day of the month.'); }
Output
Date d1 is the last day of the month. Date d2 is not the last day of the month.
In this example, two Date objects are created. The first Date object d1 represents 29th February of 2020. Because it is the last day of the month, adding 1 day to it results in 1st March.
On the other hand, the second Date object d2 represents 30th March. You know that there are 31 days in March and this date object is not the last day of the month, so adding 1 day to it results in 31st March.