3

I need to check difference between two dates - from db and actual, but in minutes in JS/jQuery (I need to run function to check by ajax).
This is format of my date:

19-01-2016 22:18

I need something like this:

if ( (date_actual - date_db) < 1 minute ) {
   //do something
}

How can I do this?

EDIT: I created something like this, but I always getting same log, it's not change - http://jsbin.com/xinaki/edit?js,console

EDIT 2: Here it's working code, BUT now it's checking in the same hour/minute, ex. 12:50:50 and 12:50:58 show log only for this 2 seconds, but I need to 'stay' log on 1 minute
http://jsbin.com/laruro/edit?js,console

Damian
  • 525
  • 2
  • 11
  • 24

2 Answers2

2

Assuming all dates are in the same format, and that they are strings, you could use this helper function to convert one or both of the strings to a real Date() object:

var makeDate = function(dateString) {
  var d = dateString.split(/[\s:-]+/);
  return new Date(d[2],d[1] - 1,d[0],d[3],d[4]);
}

And then use it like so to compare a string to the current date:

var diffInMin = function(dateString) {
  return ( new Date() /* < current date */ - makeDate(dateString) ) / ( 1000 * 60 );
};

or like this to compare two date strings:

var diffInMin = function(dateString1, dateString2) {
  // this assumes date string one will always be more recent than DateString2
  return ( makeDate(dateString1) - makeDate(dateString2) ) / ( 1000 * 60 ); 
};
pedrotp
  • 308
  • 1
  • 7
  • what if the dates are `19-01-2016 22:18` and `19-01-2017 22:18` your diff will be `0` – avrahamcool Feb 07 '16 at 22:55
  • @avrahamcool thanks for catching that, I think this new solution should work – pedrotp Feb 08 '16 at 06:39
  • @avrahamcool It's good! But ... I need to check 1 min. between two dates. Now it's checking in the same time, ex. 12:50:50 and 12:50:58 show log only for this 2 seconds, but I need to 'stay' log on 1 minute – Damian Feb 08 '16 at 11:31
  • @Vertisan not sure this is what you mean but if you want it to only log every minute then you can change the delay on the `setInterval` function from 1000 to 60000 – pedrotp Feb 08 '16 at 20:29
0

Try this function

function diffInMin(dateString1, dateString2){
  return (+ new Date(dateString2) - new Date(dateString1))/(1000*60)
}
Viktor Kukurba
  • 1,360
  • 9
  • 14