我有两个日期变量,我想比较天或小时的差异:
var old_date = 20160120030136;
var new_date = 20160123190443;
我的问题是,如何使用JS / jQuery检查new_date
和old_date
之间的天数或小时数的差异?
答案 0 :(得分:1)
function calc() {
var old_date = parseDate(document.all['old_date'].value);
var new_date = parseDate(document.all['new_date'].value);
var diff = new_date-old_date;
document.all['diff_days'].innerText = Math.ceil(diff/1000/60/60/24);
document.all['diff_hours'].innerText = Math.ceil(diff/1000/60/60);
document.all['diff_minutes'].innerText = Math.ceil(diff/1000/60);
}
function parseDate(dateString) {
return new Date(dateString.substring(0,4),
dateString.substring(4,6),
dateString.substring(6,8),
dateString.substring(8,10),
dateString.substring(10,12),
dateString.substring(12,14));
}
<div>Note: months are 0-based, so January is 0</div>
<label for="old_date">Old Date</label><input id="old_date" type="text" value="20160120030136"/>
<br/>
<label for="new_date">New Date</label><input id="new_date" type="text" value="20160123190443"/>
<br/>
<button onclick="calc()">Calculate</button>
<div>Note: fractions are rounded up</div>
<div>New minus Old in days:<span id="diff_days"></span></div>
<div>New minus Old in hours:<span id="diff_hours"></span></div>
<div>New minus Old in minutes:<span id="diff_minutes"></span></div>