我知道这个问题已经被问过一千次了,但我试图让 javascript 显示两个日期之间的天数。我看过这个帖子:How do i get the number of days between two dates in javascript
来 self 使用此代码的评论之一:
<input type="text" name="sod" class="startd" value="10/02/2016" />
<input type="text" name="dos" class="endd" value="12/02/2016" />
<script>
function treatAsUTC(date) {
var result = new Date(date);
result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
return result;
}
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (treatAsUTC(endDate) - treatAsUTC(startDate)) / millisecondsPerDay;
}
alert(daysBetween($('.startd').val(), $('.endd').val()));
</script>
JavaScript 的结果给出 61 天,但我希望它读取为 dd/mm/yyyy,而不是当前的 mm/dd/yyyy,因此结果应该是 2 天。
我尝试删除 treatAsUTC 部分,但它根本没有给出任何答案。
function daysBetween(startDate, endDate) {
var millisecondsPerDay = 24 * 60 * 60 * 1000;
return (endDate - startDate) / millisecondsPerDay;
}
alert(daysBetween($('.startd').val(), $('.endd').val()));
任何人都可以帮助或引导我走向正确的方向吗?
提前致谢。
伊恩
最佳答案
The reulst from the javascript give 61 days, but I want it to read as dd/mm/yyyy not mm/dd/yyyy as it currently is, so the result should be 2 days.
所以你只需要正确解析日期即可。原文是:
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
它解析 m/d/y 格式的日期,因此要支持 d/m/y,只需将最后一行更改为:
return new Date(mdy[2], mdy[1]-1, mdy[0]);
稍微整理一下代码,您可能会得到如下结果:
// Parse a date in d/m/y format as UTC
function treatAsUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[2], b[1]-1, b[0]));
}
function daysBetween(startDate, endDate) {
startDate = treatAsUTC(startDate);
endDate = treatAsUTC(endDate);
return (endDate - startDate) / 8.64e7;
}
function calcDiff() {
document.querySelector('#result').value =
(daysBetween(document.querySelector('#sod').value,
document.querySelector('#dos').value));
}
<input type="text" id="sod" class="startd" value="10/02/2016" />d/m/y
<input type="text" id="dos" class="endd" value="12/02/2016" />d/m/y
<br>
<button onclick="calcDiff()">Calculate difference in days</button>
<input type="text" id="result" readonly>Days
但您实际上并不需要 UTC,您只需对结果进行四舍五入即可。如果解析日期,毫秒只会在夏令时变化时出现,四舍五入到最接近的全天可以解决这个问题。但我认为使用 UTC 很好,因为它不需要舍入。
关于javascript - GMT 和欧洲格式的日期之间的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35292739/