Check if a Date is Yesterday using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 25, 2022

banner

Photo from Unsplash

Check if a Date is Yesterday using JavaScript #

To check if a date is yesterday:

  1. Subtract 1 day from the current date to get yesterday's date.
  2. Use the toDateString() method to compare the dates.
  3. If the method returns 2 equal strings, the date is yesterday.
index.js
function isYesterday(date) { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); // 👇️ Yesterday's date console.log(date); if (yesterday.toDateString() === date.toDateString()) { return true; } return false; } const y = new Date(); y.setDate(y.getDate() - 1); console.log(isYesterday(y)); // 👉️ true console.log(isYesterday(new Date('2022-01-21'))); // 👉️ false

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

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

Once we have the current date, we have to subtract 1 day from it to get yesterday's date.

The setDate() method takes a number that represents the day of the month and sets the value on the given Date instance.

The Date object in JavaScript automatically handles the scenario where subtracting or adding X days to the date pushes us into the previous/next month or year and adjusts the values.

Now that we have yesterday's date, all we have to do is compare the date to the passed in date, ignoring the time.

The toDateString method returns the date portion of a Date object in human-readable form.

index.js
// 👇️ Tue Jan 25 2022 console.log(new Date().toDateString());

If the method returns the same string for yesterday's date and the passed in date, then the passed in date is yesterday's date.

It is very important to ignore the hours, minutes, seconds and milliseconds when comparing the two dates because if you don't, you'd be comparing a date to a specific moment in time.
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.