简体   繁体   中英

Display the time input using Moment.js

I am stuck in my code in something easy but I can't solve it.

I am trying to subtract two times without the date, and I figured out how to do it

but I want to display the time in the input also not just the result

Here is what i want to show

var startTime=moment("06:51 am", "HH:mm a");
var endTime=moment("04:16 pm", "HH:mm a");

These are the two input I want to display. I tried the var startTime and endTime but it did not work. I want 06:51 am and 04:16 pm to be display

JS code:

<script>
  function myFunction() {
    var startTime = moment("06:51 am", "HH:mm a");

    var endTime = moment("04:16 pm", "HH:mm a");
    var duration = moment.duration(endTime.diff(startTime));
    var hours = parseInt(duration.asHours());
    var minutes = parseInt(duration.asMinutes()) - hours * 60;

    document.getElementById("p").innerHTML =
      hours + " hour and " + minutes + " minutes.";
  }
</script>

You need to .textContent to display the time in your div or where you want.

Its not ideal to use .innerHTML - Read more why its not here

For moment js to diplay time only use .format function available in moment.js

Run snippet below to see it working.

 function myFunction() { var startTime = moment("06:51 am", "HH:mm a"); var endTime = moment("04:16 pm", "HH:mm a"); var duration = moment.duration(endTime.diff(startTime)); var hours = parseInt(duration.asHours()); var minutes = parseInt(duration.asMinutes()) - hours * 60; document.getElementById("start").textContent = 'Start = ' +startTime.format('HH:mm a'); document.getElementById("end").textContent = 'End = ' +endTime.format('h:mm a'); document.getElementById("time").textContent = 'Difference ' +hours+ ' hour and '+ minutes+' minutes.'; } myFunction()
 <script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script> <span id="start"></span> <br> <span id="end"></span> <div id="time"> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM