例如,在输入框中给定两个日期:
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
如何在JavaScript中获得两个日期之间的天数?
例如,在输入框中给定两个日期:
<input id="first" value="1/1/2000"/>
<input id="second" value="1/1/2001"/>
<script>
alert(datediff("day", first, second)); // what goes here?
</script>
如何在JavaScript中获得两个日期之间的天数?
当前回答
1970-01-01之前和2038-01-19之后的贡献
function DateDiff(aDate1, aDate2) {
let dDay = 0;
this.isBissexto = (aYear) => {
return (aYear % 4 == 0 && aYear % 100 != 0) || (aYear % 400 == 0);
};
this.getDayOfYear = (aDate) => {
let count = 0;
for (let m = 0; m < aDate.getUTCMonth(); m++) {
count += m == 1 ? this.isBissexto(aDate.getUTCFullYear()) ? 29 : 28 : /(3|5|8|10)/.test(m) ? 30 : 31;
}
count += aDate.getUTCDate();
return count;
};
this.toDays = () => {
return dDay;
};
(() => {
let startDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate1.toISOString()) : new Date(aDate2.toISOString());
let endDate = aDate1.getTime() <= aDate2.getTime() ? new Date(aDate2.toISOString()) : new Date(aDate1.toISOString());
while (startDate.getUTCFullYear() != endDate.getUTCFullYear()) {
dDay += (this.isBissexto(startDate.getFullYear())? 366 : 365) - this.getDayOfYear(startDate) + 1;
startDate = new Date(startDate.getUTCFullYear()+1, 0, 1);
}
dDay += this.getDayOfYear(endDate) - this.getDayOfYear(startDate);
})();
}
其他回答
从DatePicker小部件使用formatDate怎么样?您可以使用它来转换时间戳格式的日期(从01/01/1970开始的毫秒),然后做一个简单的减法。
下面是datediff的快速实现,作为解决问题的概念证明。它依赖于这样一个事实,即您可以通过减去两个日期之间经过的毫秒,这将它们强制转换为原始数字值(自1970年初以来的毫秒)。
/** * Take the difference between the dates and divide by milliseconds per day. * Round to nearest whole number to deal with DST. */ function datediff(first, second) { return Math.round((second - first) / (1000 * 60 * 60 * 24)); } /** * new Date("dateString") is browser-dependent and discouraged, so we'll write * a simple parse function for U.S. date format (which does no error checking) */ function parseDate(str) { var mdy = str.split('/'); return new Date(mdy[2], mdy[0] - 1, mdy[1]); } alert(datediff(parseDate(first.value), parseDate(second.value))); <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/>
You should be aware that the "normal" Date APIs (without "UTC" in the name) operate in the local timezone of the user's browser, so in general you could run into issues if your user is in a timezone that you don't expect, and your code will have to deal with Daylight Saving Time transitions. You should carefully read the documentation for the Date object and its methods, and for anything more complicated, strongly consider using a library that offers more safe and powerful APIs for date manipulation.
数字和日期——MDN JavaScript指南 日期——MDN JavaScript参考
同样,出于说明的目的,为了简洁起见,该代码段对窗口对象使用了命名访问,但在生产中应该使用getElementById之类的标准化api,或者更有可能使用一些UI框架。
function timeDifference(date1, date2) { var oneDay = 24 * 60 * 60; // hours*minutes*seconds var oneHour = 60 * 60; // minutes*seconds var oneMinute = 60; // 60 seconds var firstDate = date1.getTime(); // convert to milliseconds var secondDate = date2.getTime(); // convert to milliseconds var seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds // the difference object var difference = { "days": 0, "hours": 0, "minutes": 0, "seconds": 0, } //calculate all the days and substract it from the total while (seconds >= oneDay) { difference.days++; seconds -= oneDay; } //calculate all the remaining hours then substract it from the total while (seconds >= oneHour) { difference.hours++; seconds -= oneHour; } //calculate all the remaining minutes then substract it from the total while (seconds >= oneMinute) { difference.minutes++; seconds -= oneMinute; } //the remaining seconds : difference.seconds = seconds; //return the difference object return difference; } console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));
简单、容易、复杂。此函数将每1秒调用一次以更新时间。
const year = (new Date().getFullYear());
const bdayDate = new Date("04,11,2019").getTime(); //mmddyyyy
// countdown
let timer = setInterval(function () {
// get today's date
const today = new Date().getTime();
// get the difference
const diff = bdayDate - today;
// math
let days = Math.floor(diff / (1000 * 60 * 60 * 24));
let hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((diff % (1000 * 60)) / 1000);
}, 1000);
在撰写本文时,其他答案中只有一个正确处理DST(夏令时)转换。以下是位于加州的一个系统的结果:
1/1/2013- 3/10/2013- 11/3/2013-
User Formula 2/1/2013 3/11/2013 11/4/2013 Result
--------- --------------------------- -------- --------- --------- ---------
Miles (d2 - d1) / N 31 0.9583333 1.0416666 Incorrect
some Math.floor((d2 - d1) / N) 31 0 1 Incorrect
fuentesjr Math.round((d2 - d1) / N) 31 1 1 Correct
toloco Math.ceiling((d2 - d1) / N) 31 1 2 Incorrect
N = 86400000
虽然数学。round返回正确的结果,我认为它有点笨拙。相反,当DST开始或结束时,通过显式计算UTC偏移量的变化,我们可以使用精确的算术:
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($('#first').val(), $('#second').val()));
解释
JavaScript的日期计算很棘手,因为date对象内部存储的时间是UTC,而不是本地时间。例如,3/10/2013太平洋标准时间12:00 AM (UTC-08:00)存储为3/10/2013上午8:00 UTC, 3/11/2013太平洋夏令时12:00 AM (UTC-07:00)存储为3/11/2013上午7:00 UTC。在这一天,从午夜到午夜,当地时间在UTC只有23小时!
虽然本地时间中的一天可以大于或小于24小时,但国际标准时间中的一天总是24小时上面所示的daysBetween方法利用了这一事实,它首先调用treatAsUTC将本地时间调整为午夜UTC,然后再进行减法和除法。
1. JavaScript忽略闰秒。