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

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


当前回答

当我想在两个日期上做一些计算时,我发现了这个问题,但是日期有小时和分钟的值,我修改了@michael-liu的答案来满足我的要求,它通过了我的测试。

差异日期2012-12-31 23:00和2013-01-01 01:00应该等于1。(2小时) 差异日期2012-12-31 01:00和2013-01-01 23:00应该等于1。(46个小时)

function treatAsUTC(date) {
    var result = new Date(date);
    result.setMinutes(result.getMinutes() - result.getTimezoneOffset());
    return result;
}

var millisecondsPerDay = 24 * 60 * 60 * 1000;
function diffDays(startDate, endDate) {
    return Math.floor(treatAsUTC(endDate) / millisecondsPerDay) - Math.floor(treatAsUTC(startDate) / millisecondsPerDay);
}

其他回答

Bookmarklet版本的其他答案,提示你两个日期:

javascript:(function() {
    var d = new Date(prompt("First Date or leave blank for today?") || Date.now());
    prompt("Days Between", Math.round(
        Math.abs(
            (d.getTime() - new Date(prompt("Date 2")).getTime())
                /(24*60*60*1000)
             )
        ));
})();

简单、容易、复杂。此函数将每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);

最好还是取消夏令时吧,马斯。装天花板,数学。楼层等,使用UTC时间:

var firstDate = Date.UTC(2015,01,2);
var secondDate = Date.UTC(2015,04,22);
var diff = Math.abs((firstDate.valueOf() 
    - secondDate.valueOf())/(24*60*60*1000));

这个例子给出了109天的差异。24*60*60*1000是一天,单位是毫秒。

下面是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框架。

在撰写本文时,其他答案中只有一个正确处理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忽略闰秒。