How to check if date is x days in the past from today in JavaScript

How to check if date is x amount of days in the past from now using JavaScript

Posted by Ervin Adams on August 16, 2022

How to check if date is x days in the past from today in JavaScript

How to check if date is x amount of days in the past from now using JavaScript

Posted by Ervin Adams on August 16, 2022

Here is one way in which you can get x number of days in the past from current date:

Step 1. Get value of a day in milliseconds

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

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

Step 4. Then convert date object into milliseconds

Step 5. Subtract date to be checked from x number of days

Here are a couple of examples below:

function pastAmountOfDays (dte, x) {
  const day = 1000 * 60 * 60 * 24; // get one day in milliseconds
  let now = new Date(); //get today's date
  let checkDate = new Date(dte); // convert date string to object
  now = new Date(now.getTime() - (x * day)); //difference between x date and date being checked in milliseconds
  return checkDate.getDate() < now.getDate(); // if date being checked is still greater than today's date then we are past x days
}

console.log(pastAmountOfDays("2022-08-12", 3)); //true
console.log(pastAmountOfDays("2022-08-16", 3)); //false