calculate duration between 2 values within the input

Asked

Viewed 67 times

1

Hello, I have a javascript code that helps me calculate the duration between one hour and another, I need to know how to make these values more dynamic, I want to put the input time in an input, the output time in another input and the result (Qtd of hours) in a 3rd input. Someone can help me?

Follow the code I have

<script type="text/javascript">
        var start = '21:00';
        var end = '22:20';

        s = start.split(':');
        e = end.split(':');

        min = e[1]-s[1];
        hour_carry = 0;
        if(min < 0){
                min += 60;
                hour_carry += 1;
        }
        hour = e[0]-s[0]-hour_carry;
        diff = hour + ":" + min;

        alert(diff);
</script>

1 answer

1

Well the hardest part you’ve ever done (I didn’t check the calculation), so it looks like this:

 <input id="start" type="time" name="s_time"> : Start<br/>
 <input id="end" type="time" name="e_time"> : End<br/>
 <input type="button" value="Run" onclick="calcTime()" /><br/>
 <input id="result" type="text" value=""/> : Resultado
 <script>
  function calcTime()
 {	var start = document.getElementById("start").value;
 	var end = document.getElementById("end").value;
 	s = start.split(':');
    e = end.split(':');
    min = e[1]-s[1];
    if(min < 10)
    {
     min = "0" + min;
    }
    hour_carry = 0;
    if(min < 0)
    {	min += 60;
        hour_carry += 1;
    }
    hour = e[0]-s[0]-hour_carry;
    diff = hour + ":" + min;
    var result = document.getElementById("result");
    result.value = diff;
 }
 </script>
 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.