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

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


当前回答

我也有同样的问题,但如果你在SQL查询上做的话会更好:

DateDiff(DAY, StartValue,GETDATE()) AS CountDays

查询将自动生成一个列CountDays

其他回答

JS中的日期值是datetime值。

因此,直接日期计算是不一致的:

(2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day

例如,我们需要转换第2个日期:

(2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day

该方法可以在两个日期截断轧机:

var date1 = new Date('2013/11/04 00:00:00'); var date2 = new Date('2013/11/04 10:10:10'); //less than 1 var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from.. var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from.. var daysDiff = end - start; // exact dates console.log(daysDiff); date2 = new Date('2013/11/05 00:00:00'); //1 var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from.. var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from.. var daysDiff = end - start; // exact dates console.log(daysDiff);

我建议使用moment.js库(http://momentjs.com/docs/#/displaying/difference/)。它正确地处理夏令时,通常是很好的工作。

例子:

var start = moment("2013-11-03");
var end = moment("2013-11-04");
end.diff(start, "days")
1

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

下面的解决方案将假设这些变量在代码中可用:

const startDate  = '2020-01-01';
const endDate    = '2020-03-15';

原生 JS

步骤:

设定开始日期 设定结束日期 计算的区别 将毫秒转换为天

const diffInMs   = new Date(endDate) - new Date(startDate)
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);

备注:

我知道这不是你问题的一部分,但一般来说,我不建议在香草JavaScript中做任何日期计算或操作,而是使用date-fns, Luxon或moment.js这样的库,因为有许多边缘情况。

这个简单的JavaScript回答以十进制数计算天数。此外,在使用夏令时时,它可能会遇到边缘情况


使用图书馆

- 日期-fns

const differenceInDays = require('date-fns/differenceInDays');
const diffInDays = differenceInDays(new Date(endDate), new Date(startDate));

文档:https://date-fns.org/v2.16.1/docs/differenceInDays

——国际光子

const { DateTime } = require('luxon');
const diffInDays = DateTime.fromISO(endDate).diff(DateTime.fromISO(startDate), 'days').toObject().days;

文档:https://moment.github.io/luxon/docs/class/src/datetime.js DateTime.html # instance-method-diff

——Moment.js

const moment = require('moment');
const diffInDays = moment(endDate).diff(moment(startDate), 'days');

文档:https://momentjs.com/docs/ / /显示/不同


RunKit示例

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