Get difference between defined / current hours

2

I would like to get how many hours have passed, from a certain 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 starting date, from that date I would like to start counting the hours. And the variable today has the current date.

    
asked by anonymous 24.05.2016 / 14:39

3 answers

1

Simplistic answer maybe, but if you just want the difference times 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 dates
  • / 36e5 because this value is the same as 3600000 which is 60 seconds x 60 minutes x 1000 milliseconds. This is because dates in javascript 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
    
24.05.2016 / 17:35
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");
}
    
24.05.2016 / 14:50
3

You can use the Moment.js library 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>
    
24.05.2016 / 15:23