javascript - Calculate hours between two datetime-local inputs - Stack Overflow

I'm trying to get the difference in hours between two datetime-local inputs (start and end date).

I'm trying to get the difference in hours between two datetime-local inputs (start and end date). I'm trying to do it with momentjs library without success. I know that the problem is in the format of the datetime-local inputs, but, there's any way to format it to allow Momentjs to get it and pare? Or should I try with a different library/input?

<input type="datetime-local" name="input-time" id="start-time">
<input id="end-time" type="datetime-local" onchange="myFunction()">
<input type="text" id="total-hours" placeholder="Total Hours">              

function myFunction() {
  var initialTime=document.getElementById("start-time");
  var initialTimeFormat=moment(initialTime);
  var endTime=document.getElementById("end-time");
  var endTimeFormat=moment(endTime);
  var totalHours=endTimeFormat.diff(initialTimeFormat,"hours");
  $("#total-hours").text(totalHours); 
  }

I'm trying to get the difference in hours between two datetime-local inputs (start and end date). I'm trying to do it with momentjs library without success. I know that the problem is in the format of the datetime-local inputs, but, there's any way to format it to allow Momentjs to get it and pare? Or should I try with a different library/input?

<input type="datetime-local" name="input-time" id="start-time">
<input id="end-time" type="datetime-local" onchange="myFunction()">
<input type="text" id="total-hours" placeholder="Total Hours">              

function myFunction() {
  var initialTime=document.getElementById("start-time");
  var initialTimeFormat=moment(initialTime);
  var endTime=document.getElementById("end-time");
  var endTimeFormat=moment(endTime);
  var totalHours=endTimeFormat.diff(initialTimeFormat,"hours");
  $("#total-hours").text(totalHours); 
  }
Share Improve this question edited Sep 21, 2017 at 22:41 NoxGamingQC 33 bronze badges asked Sep 21, 2017 at 18:39 SiliconMachineSiliconMachine 6061 gold badge10 silver badges22 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

I always like a vanilla option and since you only use hours we can go without a library such as moment. However it's a good library to use for paring dates and more.

As said in other answers the real problem lays in the retrieval of the values:

$("input#start-time").val()); //retrieving using jQuery.

document.getElementById("start-time").value; //retrieving using vanilla. | old
document.querySelector("#start-time").value; //retrieving using vanilla. | modern

Also the use of inline events is inadvisable. Use addEventListener.

 document.querySelector("#end-time").addEventListener("change", myFunction);

function myFunction() {
  function split(time)
  {
    var t = time.split(":");
    return parseInt((t[0] * 60), 10) + parseInt(t[1], 10); //convert to minutes and add minutes
    
  }

  //value start
  var start = split($("input#start-time").val()); //format HH:MM
  
  //value end
  var end = split($("input#end-time").val()); //format HH:MM

  totalHours = NaN;
  if (start < end)
  {
    totalHours = Math.floor((end-start)/60);
  }
  
  $("#total-hours").val(totalHours); 
  
 }
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="input-time" id="start-time" placeholder="HH:MM">
<input id="end-time" type="text" placeholder="HH:MM" >
<input type="text" id="total-hours" placeholder="Total Hours">

With date-selector (Chrome, Firefox and Edge). Here we use timestamp to pare. Get both timestamps with Date.parse. Since an input with datetime-local will always give us a correctly formatted ISO-date. Subtracting the timestamps gives us the difference in milliseconds. Some basic divisions leaves us with the amount of hours.

document.querySelector("#end-time").addEventListener("change", myFunction);

function myFunction() {

  //value start
  var start = Date.parse($("input#start-time").val()); //get timestamp

  //value end
  var end = Date.parse($("input#end-time").val()); //get timestamp

  totalHours = NaN;
  if (start < end) {
    totalHours = Math.floor((end - start) / 1000 / 60 / 60); //milliseconds: /1000 / 60 / 60
  }

  $("#total-hours").val(totalHours);

}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="datetime-local" name="input-time" id="start-time" placeholder="HH:MM">
<input id="end-time" type="datetime-local" placeholder="HH:MM">
<input type="text" id="total-hours" placeholder="Total Hours">

Your first issue is:

var initialTimeFormat=moment(initialTime);

You need to pass a value not an element to moment: change initialTime to initialTime.value

Your second issue is:

$("#total-hours").text(totalHours); 

You need to use val instead of text.

function myFunction() {
    var initialTime=document.getElementById("start-time");
    //
    // test if the start time is not empty
    //
    if (initialTime.value.trim() == '') {
        document.getElementById("start-time").focus();
        return;
    }
    var initialTimeFormat=moment(initialTime.value);
    var endTime=document.getElementById("end-time");
    var endTimeFormat=moment(endTime.value);
    var totalHours=endTimeFormat.diff(initialTimeFormat,"hours");
    $("#total-hours").val(totalHours);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.18.1/moment.min.js"></script>


<input type="datetime-local" name="input-time" id="start-time">
<input id="end-time" type="datetime-local" onchange="myFunction()">
<input type="text" id="total-hours" placeholder="Total Hours">

You got the value from the date input in a wrong way. I also added some validations. Check out this working example.

function myFunction() {

  var initialTime = $("#start-time").val();
  if (initialTime == "") {
    alert("Please add Start Time (HH : MM : SS)");
    return;
  }
  var initialTimeFormat = moment(initialTime);


  var endTime = $("#end-time").val();
  if (endTime == "") {
    alert("Please add End Time (HH : MM : SS)");
    return;
  }
  var endTimeFormat = moment(endTime);
  
  var difference = endTimeFormat.diff(initialTimeFormat,"hours"); 
  console.log("Time Difference: ", difference, " hours");  
  $("#total-hours").val(difference);

};
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/moment.js/2.18.1/moment.js"></script>

<input type="datetime-local" name="input-time" id="start-time">
<input id="end-time" type="datetime-local">
<button onclick="myFunction()">Calculate Time</button><br/><br/>
<input type="text" id="total-hours" placeholder="Total Hours">

Actually your pare two input and not there value. Here's the answer:

<input type="datetime-local" name="input-time" id="start-time">
<input id="end-time" type="datetime-local" onchange="myFunction()">
<input type="text" id="total-hours" placeholder="Total Hours">              

function myFunction() {
    var initialTime = document.getElementById("start-time").value;
    var initialTimeFormat = moment(initialTime);
    var endTime = document.getElementById("end-time").value;
    var endTimeFormat = moment(endTime);
    var totalHours = endTimeFormat.diff(initialTimeFormat,"hours");

    document.getElementById("total-hours").innerHTML = totalHours; 
 }

Try this:

function myFunction(){
    startTime = Date.parse(document.querySelector("#start-time").value);
    endTime =  Date.parse(document.querySelector("#end-time").value);
    output = document.querySelector("#total-hours");
    output.value = (((Math.abs( startTime - endTime ) / 1000)/60)/60) + "hs";
}

This convert start and end time to milliseconds, calculate the gap and then convert it to hours.

Using this HTML...

<input type="datetime-local" name="start-time" id="start-time">
<input type="datetime-local" name="end-time" id="end-time">
<input type="text" id="total-hours" placeholder="Total Hours">

... you can calculate the difference with this...

$("input#end-time").change(function() {
    var startDate = moment($("input#start-time").val());
    var endDate = moment($(this).val());
    $("input#total-hours").val(endDate.diff(startDate,'hours'));
});

This triggers the calculation only when you change the end-date (like in your example) and without validation. You should check that the input has content, etc.

I hope it helps

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742338602a4425160.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信