Rayan Suryadikara Rayan Suryadikara - 1 year ago 64
Javascript Question

Minute duration differentiation javascript

suppose I have this variable date in hour : minute : second format

var time1 = "12:34:19 PM"
var time2 = "12:29:25 PM"


How I get the differentiate (duration) from time1 and time2? And how we change it into date format to do diff process?

Answer Source

you can convert the time new Date() just prepend a date before it and

get their timestamp using getTime() and subtract them

var duration = new Date('datetime1').getTime() - new Date('datetime2').getTime()

since the timestamp is 1000 times than the result total seconds divide it by 1000

var duration = durantion/1000;

and I just create a function that format the seconds properly to makes it looks like a valid duration time

var time1 = "2016-11-02 12:34:19 PM"
var time2 = "2016-11-02 12:29:25 PM"

time1 = new Date(time1 ).getTime();
time2 = new Date(time2 ).getTime();
var duration = (time1 - time2) / 1000;

function formatTime(seconds) {
  var minutes = Math.floor(((seconds/3600)%1)*60);
  minutes = (minutes < 10) ? '0'+minutes : minutes;
  var seconds = Math.round(((seconds/60)%1)*60);
  seconds = (seconds < 10) ? '0'+seconds : seconds;
  return minutes+':'+seconds;
}

console.log('Duration: ' + formatTime(duration)+' secs')