Military time is hhmm whereas 24-hour time is hh:mm
A suitable way to accept either 2 or 2:00 is to add the :00 part if needed.
Then we can take the hour:minutes and create a date from them.
hour_start += Number(hour_start) ? ':00' : '';
hour_end += Number(hour_end) ? ':00' : '';
startTime = new Date('1-1-1 ' + hour_start);
endTime = new Date('1-1-1 ' + hour_end);
var difference = endTime - startTime;
The Date object is represented in milliseconds, so allows us to easily work out the time difference.
Then we convert the time difference from milliseconds to minutes, and work out the number of hours and minutes
difference /= 1000 * 60; // convert to minutes
var hours = Math.floor(difference / 60);
var mins = Math.floor(difference % 60);
document.getElementById('hour_total').innerHTML = showTime(hours, mins);
Displaying the time means adding an optional 0 to the hour and the minute, so we’ll use a separate function for that.
function showTime(hours, minutes) {
return ((hours < 10) ? '0' : '') + hours +
':' +
((minutes < 10) ? '0' : '') + minutes;
}
This example code also moves the onclick event out of the HTML code and into where it should be as a part of the scripting behaviour.
The form should not have a name attribute. It has meaning on elements within the form, but on the form itself it has no impact on how the form is used. Instead, an identifier has been used on the form as is advised by best practice.
Additionally, implicit label association means that most of the identifiers within the form are able to be tidied up.
Here is the full code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Time difference</title>
</head>
<body>
<form id="calculate" action="">
<div>
<p><label>Start Hour: <input type="text" name="hour_start" /></label></p>
<p><label>End Hour: <input type="text" name="hour_end" /></label></p>
<p id="hour_total"></p>
<p><input id="calculate_time" type="button" value="Calculate Time" /></p>
</div>
</form>
<script language="javascript" type="text/javascript">
function showTime(hours, minutes) {
return ((hours < 10) ? '0' : '') + hours +
':' +
((minutes < 10) ? '0' : '') + minutes;
}
function calculate_time(hour_start, hour_end) {
startTime = new Date('1-1-1 ' + hour_start);
endTime = new Date('1-1-1 ' + hour_end);
var difference = endTime - startTime;
difference /= 1000 * 60; // convert to minutes
var hours = Math.floor(difference / 60);
var mins = Math.floor(difference % 60);
document.getElementById('hour_total').innerHTML = showTime(hours, mins);
}
document.getElementById('calculate_time').onclick = function () {
var start = this.form.elements.hour_start.value;
var end = this.form.elements.hour_end.value;
calculate_time(start, end);
};
</script>
</body>
</html>