Check if a Date is in the Past using JavaScript


Borislav Hadzhiev

Last updated: Aug 30, 2022


Photo from Unsplash

Check if a Date is in the Past using JavaScript #

To check if a date is in the past:

  1. Use the Date() constructor to get the current date.
  2. Optionally set the time of the current date to midnight.
  3. Check if the date is less than the current date.
function isInThePast(date) { const today = new Date(); // 👇️ OPTIONAL! // This line sets the hour of the current date to midnight // so the comparison only returns `true` if the passed in date // is at least yesterday today.setHours(0, 0, 0, 0); return date < today; } console.log(isInThePast(new Date())); // 👉️ false console.log(isInThePast(new Date('2022-01-25'))); // 👉️ true

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

We used 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 0 (midnight).

This line is optional and enables us to check if the passed in Date is at least yesterday.

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

Here is the same example without setting the hour, minutes, seconds and milliseconds to 0.

function isInThePast(date) { const today = new Date(); return date < today; } const oneHourAgo = new Date(); oneHourAgo.setHours(oneHourAgo.getHours() - 1); console.log(isInThePast(oneHourAgo)); // 👉️ true console.log(isInThePast(new Date('2050-03-24'))); // 👉️ false
Now the function checks if the provided date is at least 1 millisecond in the past, instead of at least 1 day.

We can 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.

const date = new Date('2022-08-23'); // 👇️ 1661212800000 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.