日期时间之间的差异 [英] Difference Between Datetimes
问题描述
我在这里有一些代码来计算两个日期时间之间的小时差异。有点不知所措。代码被击中或错过,我不知道为什么。
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
和时间
正确填充,从jQuery UI datepicker和一个简单的下拉列表中获取值,下午2:30,下午2:45,下午3:00等。当日期相同时它工作正常,但是当日期不一样时,有时会增加10级。例如:
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(正确)
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(正确)
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(不正确)
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(不正确)
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(正确)
01/07/2011 10:30 am - 01/11/2011 11:00 am = 96.50 (Correct)
编辑,哦,我很抱歉。没有包含parseDate函数。
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])
);
}
编辑,好吧,所以 parseInt
是罪魁祸首。 parseInt(09)
返回0. 08
也是如此。奇怪的是, parseInt(07)
返回7.并且1-6也正确返回。有人告诉Javascript。
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.
推荐答案
问题是你的日期[1]上的parseInt()正在使用前导零。
The problem is that your parseInt() on date[1] is using the leading zero.
return new Date(
parseInt(date[2]), parseInt(date[0])-1, parseInt(date[1]),
hm[0], parseInt(hm[1])
);
当你传递像01/09/2011这样的日期时,09被解析为0,而不是9。
When you pass a date like 01/09/2011, the 09 is being parsed as 0, not 9.
这篇关于日期时间之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!