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

avatar

Borislav Hadzhiev

Tue Jan 25 20222 min read

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

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

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

We created a reusable function that checks if the passed in date is before 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 midnight, so we check if the passed in date is yesterday's date or older.

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

The last step is to return the result of checking if the passed in date is less 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-09-24'); // 👇️ 1663977600000 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 less than today's date, then it's in the past.

Use the search field on my Home Page to filter through my more than 1,000 articles.