Return in hours the difference between two dates in JAVASCRIPT

Asked

Viewed 3,833 times

4

I just saw this question here in Stack Overflow which shows how to solve my problem but in PHP. I would like to know how to calculate the difference between 2 dates and show this in hours. ex:

var d1 = new Date('2015-12-21 00:00:00').toTime();
var d2 = new Date('2015-12-19 00:00:00').toTime();
var df = Math.abs(d1-d2);

//?? agora preciso saber como retornar "48:00:00"

Someone has a light?

3 answers

7

> df/1000/60/60

df divided by 1000 (to return the number of seconds), divided by 60 (to return the number of minutes), divided by 60 (to return the number of hours).

If you want in days, divide by 24, then you will have 2 (days), as a result.

  • 1

    ok, that I should get to do the calculation. but had understood that there was a better method than this...

4

See if this code helps you:

data1 = new Date('2014/01/01');
data2 = new Date('2014/04/01');
var diferenca = Math.abs(date1 - date2); //diferença em milésimos e positivo
var dia = 1000*60*60*24; // milésimos de segundo correspondente a um dia
var total = Math.round(diferenca/dia); //valor total de dias arredondado 
var emHoras = Math.round(total*24); // valor total em Horas
console.log(emHoras);

He calculates the difference in hours.

  • 1

    Yes he calculates but will give me a full figure on how many hours. need to know also for minutes and seconds because in this system will be made a SLA control

4


People to solve my problem, I ended up creating a function like this:

function timeDiff(d1, d2) {
    var d1 = new Date(d1).getTime();
    var d2 = d2 || new Date().getTime();
    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;
}

This function will take the date you send (in default date format yyyy-mm-dd hh:mm:ss) and calculate the difference between the first and the second date. NOTE: in the function I put so that if sent only one date, it calculates using the current date to facilitate the service in my application...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.