Get Defined/Current Time Difference

Asked

Viewed 2,889 times

2

I would like to get how many hours has passed, from a given date, to the current date. For example:

day = "Thu May 19 2016 05:00:00 GMT-0300 (BRT)";
today = "tue May 23 2016 09:00:00 GMT-0300 (BRT)";

Variable day has the initial date, from that date I would like to start counting the hours. And the variable today has the current date.

3 answers

3

day = new Date("Thu May 19 2016 05:00:00 GMT-0300");
today = new Date("tue May 23 2016 09:00:00 GMT-0300");

document.write(diferencaDias(day,today));

function diferencaDias(data1, data2){
    var dif =
        Date.UTC(data1.getYear(),data1.getMonth(),data1.getDate(),0,0,0)
      - Date.UTC(data2.getYear(),data2.getMonth(),data2.getDate(),0,0,0);
      dif=Math.abs((dif / 1000 / 60 / 60));
      difH=Math.abs(today.getHours()-day.getHours());
      difM=Math.abs(today.getMinutes()-day.getMinutes());
      difS=Math.abs(today.getSeconds()-day.getSeconds());
    return ((dif+difH)+"Horas   "+difM+"Minutos    "+difS+"Segundos");
}

  • That way, it takes the days, not the hours right ? Because in the example I put, the result is 3 days and 20hs, then 92hs

  • +1 by using abs to ensure there will be no "negative" time difference. Now, Jonathan is right... removing the division by 24 at the end of the code will make him return the time, as the question asks.

  • I’ve changed it and it’s working, it’s hours, minutes and seconds apart.

3

You can use the library Moment js. and do something like this:

var today  = moment("Tue May 23 2016 09:00:00 GMT-0300 (BRT)");
var day = moment("Thu May 19 2016 05:00:00 GMT-0300 (BRT)");

var duracao = moment.duration(today.diff(day));
var horas = duracao.asHours();
console.log(horas)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

  • Says the object today does not have the diff method. Can tell me pq?

  • You installed the library?

  • Yes. But the problem is in the object today, and not in the moment. Then I guess it won’t interfere even if I hadn’t installed it.

  • Interferes with the method diff is part of moment. From one scanned in the code, maybe you’re forgetting something.

  • Example working on jsfiddle: https://jsfiddle.net/sinkz/koznnzvo/2/

1


Simplistic answer maybe, but if you just want the hours of difension you can do :

var horas = Math.abs(data_A - data_B) / 36e5;
  • Math.abs to give a positive number and thus be indifferent to the order of the dates
  • / 36e5 because that value is the same as 3600000 which is 60 seconds x 60 minutes x 1000 milliseconds. This is because javascript dates are in milliseconds.

Example:

var day = "Thu May 19 2016 05:00:00 GMT-0300 (BRT)";
var today = "tue May 23 2016 09:00:00 GMT-0300 (BRT)";

var horas = Math.abs(new Date(day) - new Date(today)) / 36e5;
alert(horas); // 100

Browser other questions tagged

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