0

I am trying to compare the time now and a time in a future date. When these times are the same I want to show a message. However, the code below is not working. I have been checking the console and now.getTime() is never the same as end.getTime(), presumably as they are in ms?

Does anyone know how to overcome this? Following this answer here I believe it should work.

function compareTimes() {
    var end = new Date("August 31, 2016 11:04:18");
    var now = new Date();

   if (now.getTime() == end.getTime()) {
       clearInterval(timer);
       document.getElementById('countup').innerHTML = 'EXPIRED!';
       return;
   }
}

setInterval(compareTimes, 1000);
Community
  • 1
  • 1
  • 1
    I think you meant `(now.getTime() >= end.getTime())`. –  Aug 31 '16 at 10:10
  • 1
    "is never the same as" --- it will be at `August 31, 2016 11:04:18`. Or it was already, just check your current time. – zerkms Aug 31 '16 at 10:10
  • 1
    @nicematt i think that's the one, checking if it is greater, or equal to –  Aug 31 '16 at 10:12
  • 2
    "When these times are the same" "i think that's the one, checking if it is greater,". The first thing you need to do **before** you start coding - is formalising task. What you asked and what you considered are different things. – zerkms Aug 31 '16 at 10:12
  • @zerkms `I think thats the one` is a figure of speech meaning that that is the approach i should have taken from the beginning. –  Aug 31 '16 at 10:15
  • Since you're comparing at the millisecond level about every second there's perhaps a 1:1,000 chance that they'll be the same. – RobG Aug 31 '16 at 22:19

1 Answers1

0

setInterval will execute the function compareTimes every second and your function will compare the times at that very instant. It is highly unlikely that both the times will be same, hence you won't be able to set your div to EXPIRED . In order to overcome this i suggest you check if the time is greater than the current time i.e if (now.getTime() > end.getTime()) then set the state as EXPIRED in your div.

Ananth Pai
  • 1,939
  • 14
  • 15