2
I am making a script that needs to return the time (hh:mm:ss) between two dates. The first date is fixed, the second is the current date.
Across of this post, can return this date difference (in hours) however, the result is not correct.
As image below, the value of minutes and seconds are not correct, the correct would be to return 05:06:36
.
Below follows code used. I have to do some conversion in minutes and seconds?
function timeDiff(d1, d2) {
var d1 = new Date(d1);
var d2 = d2 || new Date();
var df = Math.abs(d1 - d2);
var td = {
d: Math.round(df / (24 * 60 * 60 * 1000)), //dias
h: Math.round(df / (60 * 60 * 1000)), //horas
m: Math.abs(Math.round(df / (60 * 1000)) - (60 * 1000)), //minutos
s: Math.abs(Math.round(df / 1000) - 1000)
};
var result = '';
td.d > 0 ? result += td.d + ' dias ' : '';
td.h > 0 ? result += ('0' + td.h).slice(-2) + ':' : '00:';
td.m > 0 ? result += ('0' + td.m).slice(-2) + ':' : '00:';
td.s > 0 ? result += ('0' + td.s).slice(-2) : '00';
return result;
}