Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diff between two dates (datetime) in minutes [duplicate]

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

like image 431
Damian Avatar asked Aug 09 '26 16:08

Damian


1 Answers

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 ); 
};
like image 138
pedrotp Avatar answered Aug 11 '26 04:08

pedrotp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!