0

Welcome ! I have single question. How to display difference from two inputs using moment.js? For now i have this code:

<script>

 var now  = document.getElementById('dep').value;
 var then = document.getElementById('arr').value;
 document.writeln(moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss")); // 1

</script>

and its not working dont' know why

tomczas
  • 179
  • 1
  • 4
  • 20

4 Answers4

0

you can get the diff in seconds. I tried finding on the moment doc and couldnt find how to parse to a specific time format then it might need to be written.

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return pad(hours)+":"+pad(minutes)+":"+pad(secs);
}

var diff = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"), 'second')
document.writeln(hhmmss(diff))

ps. I took the snippet from How to convert seconds to HH:mm:ss in moment.js

Community
  • 1
  • 1
PunNeng
  • 234
  • 3
  • 8
0

There are many other StackOverflow question/answers about this. To help you get started I placed a snippet. This will show the difference in days. Check the docs for more information

<html>
    <body>
    <input type="date" id="dep" />
    <input type="date" id="arr" />
    <input type="button" onclick="test()" value="Test"/>
    <div id="test"></div>
   
     <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>

     <script>
         function test()
         {
             var now  = document.getElementById('dep').value;
             var then = document.getElementById('arr').value;
             document.getElementById('test').innerHTML = moment(now,"YYYY/MM/DD HH:mm:ss").diff(moment(then,"YYYY/MM/DD HH:mm:ss"), "days");
         }
     </script>
    </body>
</html>
ErazerBrecht
  • 1,583
  • 2
  • 20
  • 37
0

Use document.getElementById("Div-Tag-ID").value = .... instead of document.writeln

You can just get the difference between two DateTime values

   moment('2013-11-16') - moment('2013-11-15')

Answer would be in miliseconds. As per this its 86400000 which is 24 hours.

udarabibile
  • 503
  • 1
  • 6
  • 16
0

i assume that you wish to get the difference of times in seconds.

you can try the code below:

        var departure  = document.getElementById('dep').value;
        var arrival    = document.getElementById('arr').value;

        var startTime  = moment(departure, 'YYYY-MM-DD HH:mm:ss');
        var endTime    = moment(arrival, 'YYYY-MM-DD HH:mm:ss');

        var duration   = endTime.diff(startTime, 'seconds');

you can change the format of time, i used 'YYYY-MM-DD HH:mm:ss'