我试图计算两次之间的经过时间。当计算PM到AM时,它会给我一个负面结果,所以我需要在负数上加12小时才能得到正确的经过时间。为此,我必须添加条件if ($some_result < 0)
。它适用于PHP而不是js,我无法弄清楚原因
演示:http://jsfiddle.net/wH7sC/1/
function calculateTime() { //gets time elapsed between 2 time marks
var valuestart = $("select[name='timestart']").val();
var valuestop = $("select[name='timestop']").val();
//create date format
var timeStart = new Date("01/01/2007 " + valuestart).getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();
var hourDiff = timeEnd - timeStart;
if ( hourDiff < 0 ) { //this is not working
hourDiff += 12;
}
return hourDiff;
}
//prepare function on load
$(document).ready(function() {
$("select").change(calculateTime);
calculateTime();
});
//execute function when changing select options
$(function() {
$("select").change(function() {
$( "#result" ).val( calculateTime() );
});
});
答案 0 :(得分:4)
if
语句不是失败的。你需要添加24而不是12:
http://jsfiddle.net/sparebyte/wH7sC/2/
我建议安装Chrome,Firefox或IE9,打开javascript开发人员控制台并使用console.log(...)
功能。我不建议使用IE9,它的输出让我想要。