While not asked for in original request, I was interested in subtracting the times and correctly displaying results.
Here is an example of both addition and subtraction. Use the drop-down to setup for the add/sub testing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Untitled </title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').value = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body>
<input id="time1" value="" size="5"> Time 1 <br>
<input id="time2" value="" size="5"> Time 2
<button onclick="document.getElementById('timeSum').value = timeAddSub('time1','time2',true)">Add times</button>
<button onclick="document.getElementById('timeSum').value = timeAddSub('time1','time2',false)">Sub times</button>
<br><input id="timeSum" value="" size="5"> Result<br>
Test conditions: <select onchange="setTimes(this.value)">
<option value="|">Choose test</option>
<option value="1:45|1:30">1</option>
<option value="1:45|1:45">2</option>
<option value="1:30|1:45">3</option>
<option value="1:30|2:45">4</option>
<select>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() { return (this < 10) ? '0'+this : ''+this; }
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
var tt1 = ''; if (diff < 0) { tt1 = '-'; } // check for negative value
return tt1+t1.join(':');
}
</script>
</body>
</html>
Them: Why did I do it?
Me: Just for the fish.
Them: What fish?
Me: Just for the halibut. 