0

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?

4
  • Date can be represented as ticks. Convert your date2 to a Date then add/substract the number of ticks that represents 24 hours. Then it is a comparison on Date instead of splitting and parsing strings. stackoverflow.com/q/1050720/2030565 Commented Feb 25, 2021 at 20:55
  • @Jasen what ticks represent 24 hours? In my case it has to be at least 24 hours Commented Feb 25, 2021 at 21:18
  • Did you see the linked question? Commented Feb 25, 2021 at 21:25
  • Yes, but the question does not involve a time range, but a specific time Commented Feb 26, 2021 at 8:43

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.