例如,在输入框中给定两个日期:

<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中获得两个日期之间的天数?


当前回答

如果我们想计算我们的年龄,这是一个有点不同的答案

    {
      birthday: 'April 22, 1993',
      names: {
        first: 'Keith',
        last: 'Buckley'
      }
    },
    {
      birthday: 'January 3, 1975',
      names: {
        first: 'Larry',
        last: 'Heep'
      }
    },
    {
      birthday: 'February 12, 1944',
      names: {
        first: 'Linda',
        last: 'Bermeer'
      }
    }
  ];
const cleanPeople = people.map(function ({birthday, names:{first, last}}) {
      // birthday, age, fullName;
      const now = new Date();
      var age =  Math.floor(( Date.parse(now) - Date.parse(birthday)) / 31536000000);
      return {
        age,
        fullName:`${first} ${last}`
      }
    });
    console.log(cleanPeople);
    console.table(cleanPeople);

其他回答

我认为解决方案不是100%正确的,我会使用天花板而不是地板,圆形将工作,但这不是正确的操作。

function dateDiff(str1, str2){
    var diff = Date.parse(str2) - Date.parse(str1); 
    return isNaN(diff) ? NaN : {
        diff: diff,
        ms: Math.ceil(diff % 1000),
        s: Math.ceil(diff / 1000 % 60),
        m: Math.ceil(diff / 60000 % 60),
        h: Math.ceil(diff / 3600000 % 24),
        d: Math.ceil(diff / 86400000)
    };
}

如果你想有一个DateArray日期试试这个:

<script>
        function getDates(startDate, stopDate) {
        var dateArray = new Array();
        var currentDate = moment(startDate);
        dateArray.push( moment(currentDate).format('L'));

        var stopDate = moment(stopDate);
        while (dateArray[dateArray.length -1] != stopDate._i) {
            dateArray.push( moment(currentDate).format('L'));
            currentDate = moment(currentDate).add(1, 'days');
        }
        return dateArray;
      }
</script>

调试片段

夏令时问题使这里的许多答案无效。我将使用一个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");

使用毫秒时要小心。

date.getTime()返回毫秒,用毫秒做数学运算需要包含

日光节约时间(DST) 检查两个日期的时间是否相同(小时,分钟,秒,毫秒) 请确定需要哪些天数差异:2016年9月19日- 2016年9月29日= 1天或2天的差异?

上面评论中的例子是我迄今为止找到的最好的解决方案 https://stackoverflow.com/a/11252167/2091095。但是,如果你想计算所有涉及的天数,则对其结果使用+1。

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;
}

var diff = daysBetween($('#first').val(), $('#second').val()) + 1;

我从其他答案中得到一些灵感,使输入具有自动卫生。我希望这是对其他答案的改进。

我还推荐使用<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>