8

How to compare a date object in javascript to check if the object is at least 5 minutes old? I tried:

//current date
var date = new Date();
//data from database
console.log("db: " + data_from_database)
console.log("current date: " + date)

//how to check if "data_from_database is at least 5 minutes old?

db: Sun Jul 16 2017 23:59:59 GMT+0200 (CEST)

current date: Sun Jul 16 2017 14:12:43 GMT+0200 (CEST)

How to perform the check the simplest way without creating tons of new objects?

seikzer
  • 111
  • 1
  • 1
  • 8

2 Answers2

22

You would get the time in milliseconds when you subtract two dates and then you can compare

var date = new Date();
//data from database
console.log("db: " + data_from_database)
console.log("current date: " + date)

var FIVE_MIN=5*60*1000;

if((date - new Date(date_from_database)) > FIVE_MIN) {
   console.log('Delayed by more than 5 mins');
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
2
var date1 = new Date();
var date2 = new Date(data_from_database);
if(date1-date2 > 5*60*1000){
   do something
}
Killer Death
  • 459
  • 2
  • 10