在 JavaScript 中,如何计算 24 小时格式的两个时间之间的差异?
08:00:00
示例:获取从到过去了多少小时23:00:00
。
下面我从两个下拉菜单中获取两个时间值,并尝试计算两个时间之间的小时差。我得到错误的结果...
工作示例:http: //jsfiddle.net/VnwF7/1/
脚本:
$(document).ready(function() {
function calculateTime() {
//get values
var valuestart = $("select[name='timestart']").val();
var valuestop = $("select[name='timestop']").val();
//create date format
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
var difference = timeEnd - timeStart;
var diff_result = new Date(difference);
var hourDiff = diff_result.getHours();
$("p").html("<b>Total Hours:</b> " + hourDiff )
}
$("select").change(calculateTime);
calculateTime();
});
HTML:
<select name="timestart">
<option value="00:00:00">12:00 am</option>
<option value="01:00:00">1:00 am</option>
<option value="02:00:00">2:00 am</option>
<option value="03:00:00">3:00 am</option>
<option value="04:00:00">4:00 am</option>
<option value="05:00:00">5:00 am</option>
<option value="06:00:00">6:00 am</option>
<option value="07:00:00">7:00 am</option>
<option value="08:00:00">8:00 am</option>
<option value="09:00:00">9:00 am</option>
<option value="10:00:00">10:00 am</option>
<option value="11:00:00">11:00 am</option>
<option value="12:00:00">12:00 pm</option>
<option value="13:00:00">1:00 pm</option>
<option value="14:00:00">2:00 pm</option>
<option value="15:00:00">3:00 pm</option>
<option value="16:00:00">4:00 pm</option>
<option value="17:00:00">5:00 pm</option>
<option value="18:00:00">6:00 pm</option>
<option value="19:00:00">7:00 pm</option>
<option value="20:00:00">8:00 pm</option>
<option value="21:00:00">9:00 pm</option>
<option value="22:00:00">10:00 pm</option>
<option value="23:00:00">11:00 pm</option>
</select>
<select name="timestop">
<option value="00:00:00">12:00 am</option>
<option value="01:00:00">1:00 am</option>
<option value="02:00:00">2:00 am</option>
<option value="03:00:00">3:00 am</option>
<option value="04:00:00">4:00 am</option>
<option value="05:00:00">5:00 am</option>
<option value="06:00:00">6:00 am</option>
<option value="07:00:00">7:00 am</option>
<option value="08:00:00">8:00 am</option>
<option value="09:00:00">9:00 am</option>
<option value="10:00:00">10:00 am</option>
<option value="11:00:00">11:00 am</option>
<option value="12:00:00">12:00 pm</option>
<option value="13:00:00">1:00 pm</option>
<option value="14:00:00">2:00 pm</option>
<option value="15:00:00">3:00 pm</option>
<option value="16:00:00">4:00 pm</option>
<option value="17:00:00">5:00 pm</option>
<option value="18:00:00">6:00 pm</option>
<option value="19:00:00">7:00 pm</option>
<option value="20:00:00">8:00 pm</option>
<option value="21:00:00">9:00 pm</option>
<option value="22:00:00">10:00 pm</option>
<option value="23:00:00">11:00 pm</option>
</select>
<p></p>