maybeyourneighour
maybeyourneighour

Reputation: 494

check for time difference in javascript

I have an array of times in the format "2021-02-25T12:30:00" and I need to put them into a new array only if the day and time is at least 24 hours ahead. I tried this code to check for the condition, but there is some error.

date2 = "2021-02-26T12:30:00"

function getFormattedDate() {
  var date = new Date();
  var str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "T" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
  return str;
}

if ((Math.abs(new Date(date2.slice(-8)) - new Date(getFormattedDate().slice(-8))) / 36e5) >= 24) {
  console.log("Enough time")
} else {
  console.log("Not enough time")
}
console.log(date2.slice(-8))

Can someone see the error?

Upvotes: 0

Views: 46

Answers (1)

barbarbar338
barbarbar338

Reputation: 636

You can try something like this

const hrs24 = 1000 * 60 * 60 * 24; // 24 hrs in ms
const date2 = "2021-02-26T12:30:00";

if (new Date(date2).getTime() - Date.now() >= hrs24)
    console.log("Enough time");
else
    console.log("Not enough time");

Upvotes: 1

Related Questions