How to validate date if is the last day of the month with JavaScript?

Sometimes, we want to validate date if is the last day of the month with JavaScript.

In this article, we’ll look at how to validate date if is the last day of the month with JavaScript.

How to validate date if is the last day of the month with JavaScript?

To validate date if is the last day of the month with JavaScript, we can check if the date plus 1 day is in the same month as the original date.

For instance, we write:

const isLastDay = (dt) => {
  const test = new Date(dt.getTime())
  const month = test.getMonth();
  test.setDate(test.getDate() + 1);
  return test.getMonth() !== month;
}

console.log(isLastDay(new Date(2022, 0, 1)))
console.log(isLastDay(new Date(2022, 0, 31)))

to define the isLastDay function that takes the JavaScript date dt.

In it, we create a copy of dt with new Date(dt.getTime()).

Then we get the month from test with getMonth.

Next, we call test.setDate to increment test‘s date by 1.

Then we check if test is the same month as dt with test.getMonth() !== month.

Therefore, the first console log logs false and the 2nd one logs true.

Conclusion

To validate date if is the last day of the month with JavaScript, we can check if the date plus 1 day is in the same month as the original date.