Sometimes, we want to get last day of the month with JavaScript.
In this article, we’ll look at how to get last day of the month with JavaScript.
How to get last day of the month with JavaScript?
To get last day of the month with JavaScript, we can use the Date
constructor.
For instance, we write:
const lastDayOfMonth = (year, month) => {
return new Date((new Date(year, month, 1)) - 1);
}
console.log(lastDayOfMonth(2022, 11))
to create a Date
with the last day of the month as its value.
In it, we create a Date
instance with the date of the first day of the next month with (new Date(year, month, 1)
.
Then we subtract that by 1 to return the timestamp of the last minute of the last day of the last month.
And we use the returned timestamp to create a new Date
instance.
Therefore, the console log is Wed Nov 30 2022 23:59:59 GMT-0800 (Pacific Standard Time)
.
Conclusion
To get last day of the month with JavaScript, we can use the Date
constructor.