Like many before me I am tryin gto calculate the difference between two times ( Start and end time for a job)
I've created the code below but for some reason am getting a weird answer. I suspect it is to do with creating a Date object with no date in it.
Any pointers would be very educational as to why I'm getting a dud answer.
my code:
// Add in a rightStr() function so we can pad single number answers to two digit answers
function rightStr( myString, numChars){
return myString.slice( numChars * -1 );
}
// Input is 12:00 AM and 2:15 AM from jquery date pickers
function get_time_diff( starttime, endtime )
{
var starttime = typeof starttime !== 'undefined' ? starttime : "2014-01-01 00:00:00";
var endtime = typeof endtime !== 'undefined' ? endtime : "2014-01-01 00:00:00";
var starttime = new Date( "01/01/2000 " + starttime ).getTime();
var endtime = new Date( "01/01/2000 " + endtime ).getTime();
// Values show as 946638000000 - start
// 946646100000 - end
if( isNaN(starttime) )
{
return "";
}
if( isNaN(endtime) )
{
return "";
}
if (starttime <= endtime) {
var milisec_diff = endtime - starttime;
}else{
var milisec_diff = 0; // We don't allow negative returns
}
// milisec_diff is 8100000
// Which is 2.25 if it is divided by 60 * 60 * 1000 ( secs, mins, millisecs)
// this is a correct answer so far.
var date_diff = new Date( milisec_diff );
// date_diff = Thu Jan 01 1970 15:15:00 GMT+1300 (New Zealand Standard Time)
// this is where it goes wrong.
var hh = rightStr("0" + date_diff.getHours().toString(), 2) ;
var mm = rightStr("0" + date_diff.getMinutes().toString(), 2) ;
return hh + ":" + mm + ":00"
// returns 15:15
}