Calculate Time Difference Between Two Date in Hh:Mm:Ss JavaScript

calculate time difference between two date in HH:MM:SS javascript

To convert H:M:S to seconds, you can use a simple function like:

// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}

Then to convert seconds back to HMS:

// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}

var a = '01:43:28';
var b = '12:22:46';

console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18

You may want to abbreviate the function names to say:

toHMS(toSec(a) - toSec(b));  // -10:39:18

Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.

Edit

The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.

If you have Date objects, you can get the difference between them in milliseconds using:

var diffMilliseconds = date0 - date1;

and convert to seconds:

var diffSeconds = diffMilliseconds / 1000;

and present as HH:MM:SS using the secondsToHMS function above:

secondsToHMS((date0 - date1) / 1000);

e.g.

var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);

console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18

Hour difference between two times(HH:MM:SS a)in momentjs

Get Hours

I got the hours by using this code

endTime.diff(startTime, 'hours')
Get Minutes

i got the minutes by using this below code

var mins = moment.utc(moment(endTime, "HH:mm:ss").diff(moment(startTime, "HH:mm:ss"))).format("mm")
My Working code is
$scope.UpdateTimeSheet = function (rowEntity) {   
if (rowEntity.StartTime.toString().length != 11) {
rowEntity.StartTime = moment(rowEntity.StartTime).format("hh:mm:ss a");
}

if (rowEntity.EndTime.toString().length != 11) {
rowEntity.EndTime = moment(rowEntity.EndTime).format("hh:mm:ss a");
}

var startTime = moment(rowEntity.StartTime, "hh:mm:ss a");
var endTime = moment(rowEntity.EndTime, "hh:mm:ss a");

var mins = moment.utc(moment(endTime, "HH:mm:ss").diff(moment(startTime, "HH:mm:ss"))).format("mm")

rowEntity.TotalHours = endTime.diff(startTime, 'hours') + " Hrs and " + mins + " Mns";

}

How to Calculate difference between two dates with yyyy'-‘MM'-‘dd'T'HH':'mm':'ss.fffffff date-time format

const date1 = new Date("2021-02-23T08:31:37.1410141"); 
const date2 = new Date();
const diffTime = date2.getTime() - date1.getTime();
const diffDays = Math.floor(Math.abs(diffTime / (1000 * 3600 * 24)));

get the time difference between two times in format hh:mm:ss

You can split them with : and take difference. And again join them with :

    var start = '01:00:24';var end = '01:00:34';var diff = start.split(':').map((item,index) => end.split(':')[index] - item).join(':')console.log(diff)

Calculate time difference from two time inputs in HH:MM:SS format in Javascript

You can split each time string on : and then convert it to seconds in order to calculate the difference.

function timeFunction() {
const getSeconds = s => s.split(":").reduce((acc, curr) => acc * 60 + +curr, 0);
var seconds1 = getSeconds(document.getElementById("timeOne").value);
var seconds2 = getSeconds(document.getElementById("timeTwo").value);

var res = Math.abs(seconds2 - seconds1);

var hours = Math.floor(res / 3600);

var minutes = Math.floor(res % 3600 / 60);

var seconds = res % 60;
document.getElementById("timeDifference").innerHTML = hours + ":" + minutes + ":" + seconds;
}
<input type="time" id="timeOne" name="timeOne" value="00:00:01" step="1" onchange="timeFunction()">
<input type="time" id="timeTwo" name="timeTwo" value="00:00:01" step="1" onchange="timeFunction()">
<b>Time Difference: </b>
<p id="timeDifference">--:--:--</p>
<input type="hidden" id="timeDiff" name="timeDiff">

Calculate Hours Between two Date/Time Strings(YYYY-mm-dd HH:MM:SS) using Javascript

var startDate = new Date('2016-01-01 00:00:00');
var endDate = new Date('2016-01-02 23:15:00');
var time = endDate - startDate;
console.log(time/1000/60/60%24); //23.25

like this can calculate the hours span.

Calculate Date/Time Difference between two dates("yyyy-mm-dd hh-mm-ss") in WSO2 EI 6.5.0 using script mediator

Difference between two times in format (hh: mm: ss)

Highly recommend you include moment.js in your project if you need to handle time.

Example:

var t1 = moment('05:34:01', "hh:mm:ss");
var t2 = moment('20:44:44', "hh:mm:ss");
var t3 = moment(t2.diff(t1)).format("hh:mm:ss");

Working jsFiddle

To install moment.js in Node.js, simply do:

npm install moment (or for a global install sudo npm -g install moment)

And then in your Node.js, include it like so:

var moment = require('moment');

Edit: For 24h clock, change hh to HH.

Get time difference between two dates in seconds

The Code

var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;

Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.



The explanation

You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00



Rant

Depending on what your date related operations are, you might want to invest in integrating a library such as date.js or moment.js which make things so much easier for the developer, but that's just a matter of personal preference.

For example in moment.js we would do moment1.diff(moment2, "seconds") which is beautiful.



Useful docs for this answer

  • Why 1970?
  • Date object
  • Date's getTime method
  • Date's getDate method
  • Need more accuracy than just seconds?


Related Topics



Leave a reply



Submit