Check if a Date is in the Future using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 26, 2022

banner

Photo from Unsplash

Check if a Date is in the Future using JavaScript #

To check if a date is in the future:

  1. Use the Date() constructor to get the current date.
  2. Optionally set the time of the current date to the last millisecond.
  3. Check if the date is greater than the current date.
index.js
function isInTheFuture(date) { const today = new Date(); // 👇️ OPTIONAL! // This line sets the time of the current date to the // last millisecond, so the comparison returns `true` only if // date is at least tomorrow today.setHours(23, 59, 59, 998); return date > today; } const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); console.log(isInTheFuture(tomorrow)); // 👉️ true console.log(isInTheFuture(new Date('2021-01-25'))); // 👉️ false

We created a reusable function that takes a DAte object as a parameter and checks if the date is in the future.

The first thing we did is use the Date() constructor to create a Date object that represents the current date.

The next line uses the setHours method to set the hour, minutes, seconds and milliseconds of the date to the last millisecond of the current date.

This line is optional and enables us to check if the passed in Date is at least tomorrow's date.

If you remove this line, you would be checking if the passed in date is at least a millisecond in the future and not at least a day in the future.

Here is the same example without setting the hour, minutes, seconds and milliseconds to the last millisecond of the current date.

index.js
function isInTheFuture(date) { const today = new Date(); return date > today; } const oneHourInTheFuture = new Date(); oneHourInTheFuture.setHours(oneHourInTheFuture.getHours() + 1); console.log(isInTheFuture(oneHourInTheFuture)); // 👉️ true console.log(isInTheFuture(new Date('2021-01-25'))); // 👉️ false
Now the function checks if the passed in date is at least 1 millisecond in the future, instead of at least 1 day in the future.

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-10-26'); // 👇️ 1666742400000 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.
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.