Get the Last Day of a Month in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 25 20212 min read

Get the Last Day of a Month #

To get the last day of a month, use the Date() constructor to create a date object, passing it the year, the month + 1, and 0 for the day as parameters. The Date object will contain the last day of the month.

index.js
function getLastDayOfMonth(year, month) { return new Date(year, month + 1, 0); } // ๐Ÿ‘‡๏ธ Last Day of CURRENT MONTH const date = new Date(); const lastDayCurrentMonth = getLastDayOfMonth( date.getFullYear(), date.getMonth(), ); console.log(lastDayCurrentMonth); // ๐Ÿ‘‰๏ธ Mon Oct 31 2022 // ๐Ÿ‘‡๏ธ Last day of January 2025 const lastDayJan = getLastDayOfMonth(2025, 0); console.log(lastDayJan); // ๐Ÿ‘‰๏ธ Fri Jan 31 2025

We passed the following 3 parameters to the Date() constructor:

  1. The year
  2. The month - notice that we added 1 to the month to get a value representing the next month, this balances out by setting the day to 0.
  3. The day - setting the day to 0 gives us the last day of the prior month.

We used the Date.getFullYear method to get the current year.

We also used the Date.getMonth method to get the current month.

Months are zero-based in JavaScript, meaning 0 is January and 11 is December.

The reason we add 1 to the value of the month in our function, is because we want to get a value representing the next month and roll back 1 day, by specifying 0 for the day parameter to the Date object.

Going 1 month forward and 1 day back gets us the last day of the specific month.

The getLastDayOfMonth function can be used to get the last day of any month, here are some examples.

index.js
function getLastDayOfMonth(year, month) { return new Date(year, month + 1, 0); } console.log(getLastDayOfMonth(2027, 0)); // ๐Ÿ‘‰๏ธ Sun Jan 31 2027 console.log(getLastDayOfMonth(2028, 1)); // ๐Ÿ‘‰๏ธ Tue Feb 29 2028 console.log(getLastDayOfMonth(2029, 2)); // ๐Ÿ‘‰๏ธ Sat Mar 31 2029

The tricky thing to remember is - months are zero-based and go from 0 (January) to 11 (December).

If you want to make your code more readable, you can extract the value of the month into a variable.

index.js
function getLastDayOfMonth(year, month) { return new Date(year, month + 1, 0); } const january = 0; console.log(getLastDayOfMonth(2027, 0)); // ๐Ÿ‘‰๏ธ Sun Jan 31 2027

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee