I'm trying to calculate elapsed hours between two times. When calculating PM to AM it will give me a negative result so I need to add 12 hours to the negative number for correct elapsed time. For this I have to add the condition if ($some_result < 0)
. It works in php but not js, I can't figure out why
Demo: 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() );
});
});
It's not the if
statement failing. You need you add 24, not 12:
http://jsfiddle.net/sparebyte/wH7sC/2/
I recommend installing Chrome, Firefox, or IE9, opening the javascript developer console and making use of the console.log(...)
function. I don't recommend using IE9, its output leaves me wanting.