Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the difference between 2 SQLite datetimes in Javascript

I'm have a startDate and a endDate stored in a SQLite database and need to calculate the difference in minutes and seconds between the 2 datetimes using javascript.

For example:

startDate = 2012-10-07 11:01:13
endDate = 2012-10-07 12:42:13

I've had a good read though loads of similar questions on SO but could only find things relating to calculating this as part of a select.

like image 517
James J Avatar asked Sep 14 '26 13:09

James J


1 Answers

Convert the strings to a JS Date Object, subtract the dates, and use some aritmethic to calculate hours/seconds from the result. Something like:

function convertMS(ms) {
  var d, h, m, s, ts, tm, th;
  s = ts = Math.floor(ms / 1000);
  m = tm = Math.floor(s / 60);
  s = s % 60;
  h = th = Math.floor(m / 60);
  m = m % 60;
  d = Math.floor(h / 24);
  h = h % 24;
  return { d: d, h: h, m: m, s: s, tm: tm, th: th, ts: ts};
};
var start = new Date('2012-10-07 11:01:13'.split('-').join('/'))
   ,end   = new Date('2012-10-07 12:42:13'.split('-').join('/'))
   ,dif   = convertMS(end - start);
console.log(dif.h+':'+dif.m);​​​​​​ //=> ​1:41
console.log('total minutes dif: '+dif.tm);​​​​​​ //=> total ​minutes dif: 101
console.log('total seconds dif: '+dif.ts);​​​​​​ //=> ​total seconds dif: 6060

[edit based on comment]
'Manual' parsing of a date string in the provided format:

Date.tryParse = function(ds){
  var  arr =  ds.match(/\d+/g)
      ,err = 'Expected at least yyyy'
      ,dat = arr.length && String(arr[0]).length === 4
              ? doParse.apply(null,arr) : err;
  return dat;

  function doParse(y,m,d,h,mi,s,ms){
   var dat = new Date(+y,(+m-1)||0,+d||1,+h||0,+mi||0,+s||0,+ms||0);
   return isNaN(dat) ? new Date : dat;
  }
}
var start = Date.tryParse('2012-10-07 11:01:13'); //=> Sun Oct 07 2012 11:01:13
var test  = Date.tryParse('2009');                //=> Sun Jan 01 2009 00:00:00
like image 120
KooiInc Avatar answered Sep 16 '26 02:09

KooiInc