Blog

Add and Substract operations of time using Javascript

Posted by : Leo T Abraham on 12 August, 2013

The following is a working example for add and substract operations of time using Javascript. In the code what I have did is, accepted time input from the user and result is shown in a textbox. The date field has been kept as a constant here. Try the following code to see the working.

<html>
    <head>
        <title>Add and Substract operations of time using Javascript</title>
        <script type="text/javascript">
            function time()
            {
                var t1 = document.getElementById('time1').value;
                var t2 = document.getElementById('time2').value;
                var t3 = document.getElementById('time3').value;
                
                var time1 = new Date('2013/08/12 ' + t1);
                var time2 = new Date('2013/08/12 ' + t2);
                var time3 = new Date('2013/08/12 ' + t3);

                var result = Math.abs(time2.getTime() - time1.getTime()) + time3.getTime();
                var hours = new Date(result).getHours();
                var minutes = new Date(result).getMinutes();
                var seconds = new Date(result).getSeconds();
                
                document.getElementById('result').value = hours + ':' + minutes + ':' + seconds;
                
            }
        </script>
    </head>
    <body>
        <h1>Add and Substract operations of time using Javascript</h1>
        <form>
            <p>Time Format <b>hh:mm:ss</b></p>
            <p><b>hh:mm Mandatory.</b></p>
            <p>Result <b>(Time2 - Time1) + Time3</b></p>
            <label>Time 1</label>&nbsp;<input type="text" id="time1"><br><br>
            <label>Time 2</label>&nbsp;<input type="text" id="time2"><br><br>
            <label>Time 3</label>&nbsp;<input type="text" id="time3" onchange="time()"><br><br>
            <label>Result</label>&nbsp;&nbsp;<input type="text" id="result">
        </form>
    </body>
</html>