How to know if date is yesterday in JavaScript

How to know if date is yesterday using JavaScript

Posted by Ervin Adams on August 17, 2022

How to know if date is yesterday in JavaScript

How to know if date is yesterday using JavaScript

Posted by Ervin Adams on August 17, 2022

To detect that a date is yesterday using JavaScript:

Step 1. Get value of a day in milliseconds

Step 2. Get today's date using Date() object

Step 3. Subract today's date in milliseconds from day value

Step 4. Convert date string to be checked to date object within Date()

Step 5. Then convert date object into milliseconds

Step 6. Check if date to be checked is equal

Here are a couple of examples below:

function isYesterday (dte) {
  const day = 1000 * 60 * 60 * 24; // get one day in millidsecods
  let now = new Date(); //get today's date
  let checkDate = new Date(dte); // convert date string to object
  now = new Date(now.getTime() - day); //difference between a day and date being checked in milliseconds
  if(checkDate.getDate() == now.getDate()){
    return true;
  }else{
      return false;
  }
}

console.log(isYesterday("2022-08-16")); //true
console.log(isYesterday("2022-08-12")); //false