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

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


当前回答

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

其他回答

这个答案基于另一个答案(链接在最后),是关于两个日期之间的差异。 你可以看到它是如何工作的,因为它很简单,它还包括将差异分成 时间单位(我做的一个函数)并转换为UTC以停止时区问题。

function date_units_diff(a, b, unit_amounts) { var split_to_whole_units = function (milliseconds, unit_amounts) { // unit_amounts = list/array of amounts of milliseconds in a // second, seconds in a minute, etc., for example "[1000, 60]". time_data = [milliseconds]; for (i = 0; i < unit_amounts.length; i++) { time_data.push(parseInt(time_data[i] / unit_amounts[i])); time_data[i] = time_data[i] % unit_amounts[i]; }; return time_data.reverse(); }; if (unit_amounts == undefined) { unit_amounts = [1000, 60, 60, 24]; }; var utc_a = new Date(a.toUTCString()); var utc_b = new Date(b.toUTCString()); var diff = (utc_b - utc_a); return split_to_whole_units(diff, unit_amounts); } // Example of use: var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2); document.write("In difference: 0 days, 1 hours, 2 minutes.".replace( /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

我上面的代码是如何工作的

日期/时间差异,以毫秒为单位,可以使用date对象计算:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

然后算出这个差值的秒数,将其除以1000进行换算 毫秒到秒,然后将结果更改为整数(整数)以删除 毫秒数(小数的小数部分):var seconds = parseInt(diff/1000)。 此外,我可以使用相同的过程获得更长的时间单位,例如: -(整)分钟,秒除以60,结果变为整数, —hours,分钟除以60,返回结果为整数。

我创建了一个函数来完成这个过程,把差值分成 整个时间单位,命名为split_to_whole_units,演示如下:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

这个答案是基于另一个答案的。

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

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

 // JavaScript / NodeJs answer  
   let startDate = new Date("2022-09-19");
   let endDate = new Date("2022-09-26");

   let difference = startDate.getTime() - endDate.getTime();
   
    console.log(difference);

   let TotalDiffDays = Math.ceil(difference / (1000 * 3600 * 24));
   console.log(TotalDiffDays + " days :) ");

这可能不是最优雅的解决方案,但我认为它似乎用一段相对简单的代码就回答了这个问题。你不能用这样的词吗?

function dayDiff(startdate, enddate) {
  var dayCount = 0;

  while(enddate >= startdate) {
    dayCount++;
    startdate.setDate(startdate.getDate() + 1);
  }

return dayCount; 
}

这是假设您将日期对象作为参数传递。