获取两个时间之间相差多少个小时.
思路:
将两个时间转换成毫秒值相减,可以得到两个时间相差的毫秒值
通过毫秒值,将之转换成小时(除以1000/60/60)
function getInervalHour(startDate, endDate) {
var ms = endDate.getTime() - startDate.getTime();
if (ms < 0) return 0;
return Math.floor(ms/1000/60/60);
}
调用 说明,传过去的必须是两个时间,调用示例:
var startDate = new Date();
var endDate = new Date();
endDate.setMonth(endDate.getMonth()+1);
//调用方法获取两个时间相差了几个小时
alert(getIntervalHour(startDate,endDate));
完整例子,这里要引入jquery文件。自行引入。
<html>
<head>
<title>测试获取两个时间相差了几个小时</title>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<script>
//计算两个时间相差了几个小时
function getIntervalHour(startDate, endDate) {
var ms = endDate.getTime() - startDate.getTime();
if (ms < 0) return 0;
return Math.floor(ms/1000/60/60);
}
$(function(){
var startDate = new Date();
var endDate = new Date();
endDate.setMonth(endDate.getMonth()+1);
//调用方法获取两个时间相差了几个小时
alert("相差"+getIntervalHour(startDate,endDate));
})
</script>
<body>
</html>
效果图: