Check if a Date is after Today's date using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 25, 2022

banner

Photo from Unsplash

Check if a Date is after Today's date using JavaScript #

To check if a date is after today's date:

  1. Use the Date() constructor to create a new date.
  2. Optionally set the time of the date to the last millisecond of today's date.
  3. Check if the passed in date is greater than today's date.
index.js
function isAfterToday(date) { const today = new Date(); today.setHours(23, 59, 59, 998); return date > today; } const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); console.log(isAfterToday(yesterday)); // 👉️ false console.log(isAfterToday(tomorrow)); // 👉️ true console.log(isAfterToday(new Date())); // 👉️ false

We created a reusable function that checks if the passed in date is after today's date.

The first thing we did in the function is use the Date() constructor to get the current date.

The setHours method takes the hours, minutes, seconds and milliseconds as parameters and changes the values for the given Date instance.

In this line, we basically set the time of today's date to the last millisecond of the date, so we check if the passed in date is at least tomorrows's date.

If you remove the line that uses the setHours() method, you'd be checking if the Date is in the future and not necessarily tomorrow or further into the future.

The last step is to return the result of checking if the passed in date is greater than today's date.

We are able to compare the dates because under the hood each date stores a timestamp - the number of milliseconds elapsed between the 1st of January 1970 and the given date.

index.js
const date = new Date('2022-06-22'); // 👇️ 1655856000000 console.log(date.getTime());
Each date stores a timestamp under the hood, so the default behavior is to compare the timestamps of the dates, even if you don't explicitly call the getTime() method on each date.

If the passed in date is greater than today's date, then it's in the future.

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.