I've got a bit of code here that calculates the hours difference between two datetimes. Kind of at a loss here. Code is hit or miss and I'm not sure why.
var date = tr.find('td:eq(10) input').val();
var time = tr.find('td:eq(10) option:selected').val();
var d1 = parseDate(date,time);
date = tr.find('td:eq(11) input').val();
time = tr.find('td:eq(11) option:selected').val();
var d2 = parseDate(date,time);
var diff = d2.getTime() - d1.getTime();
var hoursTd = tr.find('td:eq(12)');
hoursTd.html((diff/3600000).toFixed(2));
date
and time
are populated correctly, pulling from a jQuery UI datepicker and a simple dropdown with values 2:30 pm, 2:45 pm, 3:00 pm, etc. It works fine when the date is the same, but sometimes adds a magnitude of ten when the date is not the same. For example:
01/11/2011 10:30 am - 01/11/2011 11:00 am = 0.50 (Correct)
01/10/2011 10:30 am - 01/11/2011 11:00 am = 24.50 (Correct)
01/09/2011 10:30 am - 01/11/2011 11:00 am = 264.50 (Incorrect)
01/08/2011 10:30 am - 01/11/2011 11:00 am = 264.50 (Incorrect)
01/07/2011 10:30 am - 01/11/2011 11:00 am = 96.50 (Correct)
Edit, Oh my, I'm sorry. Didn't include the parseDate function.
// Date m/d/Y Time h:m a
function parseDate(date,time) {
date = date.split("/");
time = time.split(" ");
hm = time[0].split(':');
if (parseInt(hm[0]) == 12) {
hm[0] = 0;
}
if (time[1] == 'pm') {
hm[0] = parseInt(hm[0]) + 12;
} else {
hm[0] = parseInt(hm[0]);
}
return new Date(
parseInt(date[2]), parseInt(date[0])-1, parseInt(date[1]),
hm[0], parseInt(hm[1])
);
}
Edit, ok, so parseInt
is the culprit. parseInt("09")
returns 0. So does "08"
. Strangely enough, parseInt("07")
returns 7. And 1-6 return correctly as well. Someone tell Javascript.