0
Today I came across a problem at the time of testing the differences of hours in the library of moment.js.
It works perfectly, but when I add a night job until the next day it brings me a negative time.
Code:
$("#time2").keyup(function() {
  var valor = $(this).val().length;
  if (valor === 5) {
    var hrF = document.getElementById("time2").value;
    var hrIni = document.getElementById("time1").value;
    var ms = moment(hrF, "HH:mm").diff(moment(hrIni, "HH:mm"));
    var d = moment.duration(ms);
    var s = Math.floor(d.asHours()) + ":" + moment.utc(ms).format("mm");
    document.getElementById("timedif").value = s; //Jogar o valor em um terceiro campo do tipo time
  }
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
<div class=''>
  <input type="text" class="form-control tracker1" name="time1" id="time1" placeholder="12:00" data-timepicker>
</div>
<div class='mr-2'>
  <input type="text" class="form-control tracker1" id="time2" placeholder="12:00" data-timepicker>
</div>
<div class='mr-2'>
  <input type="text" class="form-control tracker1" id="timedif" readonly>
</div>
For this account to be done correctly you also need the date with the time, example:
1999-01-01 13:00|1992-01-01 01:00without the date the calculation goes wrong !– novic