Check if a Date is the Last day of the Month in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 26, 2022

banner

Photo from Unsplash

Check if a Date is the last day of the Month in JavaScript #

To check if a date is the last day of the month:

  1. Get the timestamp of the date.
  2. Add 1 day in milliseconds to the timestamp.
  3. Check if the day of the month for the date is the 1st.
index.js
function isLastDayOfMonth(date = new Date()) { // 👇️ ms sec min hour const oneDayInMs = 1000 * 60 * 60 * 24; return new Date(date.getTime() + oneDayInMs).getDate() === 1; } console.log(isLastDayOfMonth(new Date('2022-02-28'))); // 👉️ true console.log(isLastDayOfMonth(new Date('2022-02-27'))); // 👉️ false

We created a reusable function that takes a Date object as a parameter and checks if the date is the last day of the month.

If the function is called without a parameter, it uses the current date.

The first thing we did in the function is calculate how many milliseconds there are in 1 day.

The getTime() method returns the number of milliseconds elapsed between midnight of the 1st of January 1970 and the given date.

By adding 1 day in milliseconds to the timestamp, we are able to get the timestamp for the next day.

Passing the timestamp to the Date() constructor returns a Date object that stores the next day.

The getDate() method returns a number between 1 and 31 that represents the day of the month for the given date.

If adding 1 day to the passed in date returns 1 for the day of the month, then we can be sure that the passed in date is the last day of the month.

This would work regardless of how many days the month has because adding 1 day to the last day of any month yields the first day of the next month.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.