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?
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?
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')
This is working script
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
var timeStart = new Date("Mon Jan 01 2007 11:00:00 GMT+0530").getTime();
var timeEnd = new Date("Mon Jan 01 2007 11:32:51 GMT+0530").getTime();
var hourDiff = timeEnd - timeStart; //in ms
var secDiff = (hourDiff / 1000).toString(); //in s
alert(secDiff .toHHMMSS());
You can create a Date
objects using constructor like this:
Date(year, month, date, hours, minutes, seconds, ms)
in your case you can get diff:
var date = new Date(2000, 1, 1, 12, 34, 19, 0, 0),
date2 = new Date(2000, 1, 1, 12, 39, 25, 0, 0);
console.log(date2 - date); // in ms. You can do whatever you want with this value
you can read more about Date
object here.