Javascript Difference between dates

Asked

Viewed 46 times

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.

inserir a descrição da imagem aqui

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

1 answer

1

You have to use Math.floor to always round down (instead of Math.round, which depending on the case may round up).

In addition, it is necessary to deduct the total of days, hours and minutes from the difference, before making the next division. For example, if I have 130,000 milliseconds, dividing by 60 * 1000 and round it up, I’ll have two hours. So I have to discount these two hours (i.e., subtract 120,000 milliseconds from the total), so that about 10,000 milliseconds (which equals 10 seconds). The same goes for days and hours, so it would look like this:

function format(valor) {
    return valor.toString().padStart(2, '0');
}

function timeDiff(d1, d2) {
    var d1 = new Date(d1);
    var d2 = d2 || new Date();
    var df = Math.abs(d1 - d2);
    let d = Math.floor(df / (24 * 60 * 60 * 1000)); // dias 
    df -= d * 24 * 60 * 60 * 1000; // desconta o total de dias
    let h = Math.floor(df / (60 * 60 * 1000)); // horas
    df -= h * 60 * 60 * 1000; // desconta o total de horas
    let m = Math.floor(df / (60 * 1000)); // minutos
    df -= m * 60 * 1000; // desconta o total de minutos
    let s = Math.floor(df / 1000); // segundos
    var result = '';
    if (d > 0) result = `${d} dias `;
    return `${result}${format(h)}:${format(m)}:${format(s)}`;
}

let d1 = new Date('2020-10-13T07:04:59');
let d2 = new Date('2020-10-13T12:11:35');
console.log(timeDiff(d1, d2)); // 05:06:36

I also showed another option to format the values using padStart, in addition to the use of string template as an alternative to string concatenation.

Browser other questions tagged

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