0

I have 2 dates that I want to subtract the difference then compare it to return a simple command on the output. I have it in a js for loop and then doing simple math.

My information is pulled from an API and returns from a JSON response the following:

-0: Object
dateTime: "2018-02-14T14:27:00.000Z" //This is what I want to use 
+device: Object
distanceSinceLastValidCoordinate: 0
+driver: Object
eventCode: 4
eventRecordStatus: 1
eventType: 1
id: "atyhJlpX9YEyMdDHG03EA2w"
+location: Object
malfunction: "None"
origin: "Automatic"
sequence: "00000000000006a8"
state: "Active"
status: "ON"
version: "0000000000046700"

My code is this:

    for(var i=0; i < results.length; i++){
                   var stTime = results[i].dateTime; //Returns: 2018-02-14T14:27:00.000Z


                   var status = results[i].status;
                   var driver = results[i].driver.id;

                   var today = new Date(); //Returns: 2018-02-14T15:27:27.582Z

                   console.log("Today: ",today);
                   console.log("From Database: ", stTime);


                   var answerThis =  Math.abs(stTime - today); //Retuns: NULL

                   console.log("Answer: ", answerThis)



                   if((answerThis) > 6){

                       console.log("Driver "+ driver +" on "+ stTime + " Has The Status Of " + status);
                   }
                 }
              }),function(e){
                       console.error("Failed: ",e)
                   }

It never errors out, just gives a NULL value.

My question is how can I use the dateTime value that is generated and subtract the time from NOW, then if the time is greater than 6hrs, to show the console.log() info in the IF statement?

PKershner
  • 13
  • 1
  • 8
  • Please post a "working" example. The expression `Math.abs(stTime - today)` must return a Number, which might be an integer or NaN. It should never return *null* according to [*ECMA-262*](http://ecma-international.org/ecma-262/8.0/#sec-math.abs). – RobG Feb 14 '18 at 23:03

3 Answers3

1

You can go (new Date().getTime() - stTime.getTime()) to give the difference in milliseconds.

let timeDifferenceMilliseconds = (new Date().getTime() - stTime.getTime());

let timeDifferenceHours = timeDifferenceMilliseconds / (3600*1000);

if (timeDifferenceHours > 6) {
    // Do some stuff
}
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
0

replace
var stTime = results[i].dateTime with var stTime = new Date( results[i].dateTime)

and

var answerThis = new Date(Math.abs(stTime - today));

if(answerThis.getHours() > 6){
    console.log("Driver "+ driver +" on "+ stTime + " Has The Status Of " + status);
}
theAnubhav
  • 535
  • 6
  • 16
0

Subtract the milliseconds of those two dates:

var stTime = new Date(results[i].dateTime);
var today = new Date();
var answerThis =  Math.abs(stTime.getTime() - today.getTime());

After that you could convert answerThis back to Minutes, Hours, Days, whatever you need.

mind
  • 432
  • 6
  • 18