Skip to content Skip to sidebar Skip to footer

How Do I Compare Dates In Javascript?

I have the following situation: I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop. I want to be able to check whether the l

Solution 1:

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

var diffSeconds = (newDate() - LastTimeIDidTheLoop) / 1000; 
if (diffSeconds > 30)
{
  // ...
}

Solution 2:

what about:

newDate = newDate()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
  alert("oops");
}

Solution 3:

You can do like this:

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

then:

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

Solution 4:

Create a date object and use setSeconds().

controlDate = newDate();
controlDate.setSeconds(controlDate.getSeconds() + 30);

if (LastTimeIDidTheLoop > controlDate) {
...

Post a Comment for "How Do I Compare Dates In Javascript?"