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

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


当前回答

这个答案基于另一个答案(链接在最后),是关于两个日期之间的差异。 你可以看到它是如何工作的,因为它很简单,它还包括将差异分成 时间单位(我做的一个函数)并转换为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.

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

其他回答

试试这个

let today = new Date(). toisostring()。片(0,10) const startDate = '2021-04-15'; const endDate = today; const diffInMs = new Date(endDate) - new Date(startDate) const diffInDays = diffInMs / (1000 * 60 * 60 * 24); alert(diffInDays);

最好还是取消夏令时吧,马斯。装天花板,数学。楼层等,使用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是一天,单位是毫秒。

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

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

如果你想有一个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>

调试片段