Return in hours the difference between two dates in JAVASCRIPT

3

I've just seen this question here in Stack Overflow that shows how to solve my problem but in PHP. I would like to know how I can 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"

Does anyone have a light?

    
asked by anonymous 21.12.2015 / 14:04

3 answers

3

I have a problem with 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 get the date you send (in default format for date yyyy-mm-dd hh:mm:ss ) and calculate the difference between the first and second dates. NOTE: In the function I put so that if only one date is sent, it calculates using the current date to facilitate the service in my application ...

    
21.12.2015 / 15:28
6
> 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.

    
21.12.2015 / 14:15
3

See if this code helps:

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);

It calculates the difference in hours.

    
21.12.2015 / 14:18