例如,在输入框中给定两个日期:
<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中获得两个日期之间的天数?
当前回答
夏令时问题使这里的许多答案无效。我将使用一个helper函数来获得给定日期的唯一天数——通过使用UTC方法:
const dayNumber = a => Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()) / (24*60*60*1000); const daysBetween = (a, b) => dayNumber(b) - dayNumber(a); // Testing it const start = new Date(1000, 0, 1); // 1 January 1000 const end = new Date(3000, 0, 1); // 1 January 3000 let current = new Date(start); for (let days = 0; current < end; days++) { const diff = daysBetween(start, current); if (diff !== days) throw "test failed"; current.setDate(current.getDate() + 1); // move current date one day forward } console.log("tests succeeded");
其他回答
下面是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框架。
在这种情况下使用moment会容易得多,你可以试试这个:
let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days');
它会给你一个整数值,比如1、2、5、0等,所以你可以很容易地使用条件检查,比如:
if(days < 1) {
此外,还有一件事是你可以得到更准确的时间差结果(以小数形式,如1.2,1.5,0.7等),使用以下语法得到这种结果:
let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days', true);
如果你有任何进一步的疑问,请告诉我
我只有两个以毫秒为单位的时间戳,所以我必须用moment.js做一些额外的步骤来获得天数。
const getDaysDiff = (fromTimestamp, toTimestamp) => {
// set timezone offset with utcOffset if needed
let fromDate = moment(fromTimestamp).utcOffset(8);
let toDate = moment(toTimestamp).utcOffset(8);
// get the start moment of the day
fromDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
toDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
let diffDays = toDate.diff(fromDate, 'days');
return diffDays;
}
getDaysDiff(1528889400000, 1528944180000)// 1
我来找这个小工具在里面你会找到这个的函数。这里有一个简短的例子:
<script type="text/javascript" src="date.js"></script>
<script type="text/javascript">
var minutes = 1000*60;
var hours = minutes*60;
var days = hours*24;
var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");
var diff_date = Math.round((foo_date2 - foo_date1)/days);
alert("Diff date is: " + diff_date );
</script>
我从其他答案中得到一些灵感,使输入具有自动卫生。我希望这是对其他答案的改进。
我还推荐使用<input type="date">字段,这将有助于验证用户输入。
//use best practices by labeling your constants. let MS_PER_SEC = 1000 , SEC_PER_HR = 60 * 60 , HR_PER_DAY = 24 , MS_PER_DAY = MS_PER_SEC * SEC_PER_HR * HR_PER_DAY ; //let's assume we get Date objects as arguments, otherwise return 0. function dateDiffInDays(date1Time, date2Time) { if (!date1Time || !date2Time) return 0; return Math.round((date2Time - date1Time) / MS_PER_DAY); } function getUTCTime(dateStr) { const date = new Date(dateStr); // If use 'Date.getTime()' it doesn't compute the right amount of days // if there is a 'day saving time' change between dates return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()); } function calcInputs() { let date1 = document.getElementById("date1") , date2 = document.getElementById("date2") , resultSpan = document.getElementById("result") ; if (date1.value && date2.value && resultSpan) { //remove non-date characters console.log(getUTCTime(date1.value)); let date1Time = getUTCTime(date1.value) , date2Time = getUTCTime(date2.value) , result = dateDiffInDays(date1Time, date2Time) ; resultSpan.innerHTML = result + " days"; } } window.onload = function() { calcInputs(); }; //some code examples console.log(dateDiffInDays(new Date("1/15/2019"), new Date("1/30/2019"))); console.log(dateDiffInDays(new Date("1/15/2019"), new Date("2/30/2019"))); console.log(dateDiffInDays(new Date("1/15/2000"), new Date("1/15/2019"))); <input type="date" id="date1" value="2000-01-01" onchange="calcInputs();" /> <input type="date" id="date2" value="2022-01-01" onchange="calcInputs();"/> Result: <span id="result"></span>