我正在尝试计算两次之间经过的小时数。当计算 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() );
});
});
最佳答案
这不是 if
语句失败。您需要添加 24,而不是 12:
http://jsfiddle.net/sparebyte/wH7sC/2/
我建议安装 Chrome、Firefox 或 IE9,打开 javascript 开发人员控制台并使用 console.log(...)
函数。我不推荐使用 IE9,它的输出让我想要。
关于php - javascript 如果负面条件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043169/