Date is a built-in object in Javascript that stores the date and time. It can be used to measure time and display dates.
As a developer sometimes you might get a task which involves measuring a certain span of time.
In this lesson, we will look at how to check if the date is x amount of days in the past from current date.
Here are the steps:
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 less 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
In the code snippet above the pastAmountOfDays() method contains the script to be executed.
The method takes 2 paremeter values, a date string and days passed.
The x days and now date is broken down into milliseconds.and the difference provided by the Date object.
Finally, the result is given by checking if date passed is less than current date.