获取两个日期对象之间的时差? [英] Get the hours difference between two date objects?
问题描述
尝试从更改此功能吗?/a>以小时为单位(而不是几天)返回差额,但到目前为止没有运气.=)
Trying to change this function from Get difference between 2 dates in javascript? to return difference in hours instead of days, but no luck so far. =)
function dateDiffInDays(scheduled, due) {
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
var scheduled = new Date(scheduled);
var due = new Date(due);
var utc1 = Date.UTC(scheduled.getFullYear(), scheduled.getMonth(), scheduled.getDate());
var utc2 = Date.UTC(due.getFullYear(), due.getMonth(), due.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
将 _MS_PER_DAY
更改为 1000 * 60 * 60
,但是返回零将不起作用.请帮忙.
Changed _MS_PER_DAY
to 1000 * 60 * 60
, but it wont work returning zeros. Please help.
计划值和到期时间,格式为:"2014年9月21日上午09:00:00"
values of schedule and due in this format: "09/21/2014 09:00:00 am"
推荐答案
在您的问题中,这些行是:
In your question, these lines:
var utc1 = Date.UTC(scheduled.getFullYear(), scheduled.getMonth(), scheduled.getDate());
var utc2 = Date.UTC(due.getFullYear(), due.getMonth(), due.getDate());
清理小时/分钟/等.日期中的信息,因此,如果两个日期都在同一天,则结果将始终为零.
Scrub the hour/minute/etc. information from the dates, so if the two dates fall on the same day, the result will always be zero.
可以使用更简单的函数来获取小时数差异(以十进制数表示):
A much simpler function can be used to get the difference in hours (as a decimal number):
function dateDiffInHours(date1, date2) {
var msDiff = date2.getTime() - date1.getTime();
return msDiff / 3600000;
}
或者如果您希望将其作为四舍五入的整数,则将 Math.round()
或 Math.floor()
应用于返回的结果.
Or if you want it as a rounded/floored int, then apply Math.round()
or Math.floor()
to the returned result.
完全不必转换为UTC.
Converting to UTC at all is unnecessary.
这篇关于获取两个日期对象之间的时差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!