How to compare dates in javascript?

I have the following situation:

I have a specific function that starts a loop and makes stuff, and error conditions can make it exit this loop. I want to check if everything is working cycle or not.

For this, I do for each cycle:

LastTimeIDidTheLoop = new Date();

And in another function that passes through SetInterval every 30 seconds, I want to do basically this:

if (LastTimeIDidTheLoop is more than 30 seconds ago) {
  alert("oops");
}

How to do it?

Thanks!

+3
source share
4 answers

What about:

newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
  alert("oops");
}
+5
source

JS date objects store milliseconds inside, subtracting them from each other, works as expected:

var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000; 
if (diffSeconds > 30)
{
  // ...
}
+7
source

:

var dateDiff = function(fromdate, todate) {
    var diff = todate - fromdate;
    return Math.floor(diff/1000);
}

:

if (dateDiff(fromdate, todate) > 30){
    alert("oops");
}
0

setSeconds().

controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);

if (LastTimeIDidTheLoop > controlDate) {
...
-1

All Articles