如何计算两个日期之间的天数?

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

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

705466 次浏览

从DatePicker小部件使用formatDate怎么样?您可以使用它来转换时间戳格式的日期(从01/01/1970开始的毫秒),然后做一个简单的减法。

下面是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"/>

你应该意识到,“正常”;日期api(不含“;UTC")在用户浏览器的本地时区中操作,所以通常情况下,如果您的用户在您不期望的时区,您可能会遇到问题,并且您的代码将不得不处理日光节约时间的转换。您应该仔细阅读Date对象及其方法的文档,对于任何更复杂的东西,请强烈考虑使用为日期操作提供更安全、更强大api的库。

同样,为了说明目的,代码片段使用命名访问window对象,但为了简洁起见,在生产中您应该使用标准化的api,如getElementById,或者更可能的是,使用一些UI框架。

点击使用这个小工具在这里你可以找到它的函数。这里有一个简短的例子:

        <script type="text/javascript" src="date.js"></script>
<script type="text/javascript">
var minutes = 1000*60;
var hours = minutes*60;
var days = hours*24;


var foo_date1 = getDateFromFormat("02/10/2009", "M/d/y");
var foo_date2 = getDateFromFormat("02/12/2009", "M/d/y");


var diff_date = Math.round((foo_date2 - foo_date1)/days);
alert("Diff date is: " + diff_date );
</script>

区分两个日期的最简单方法是:

var diff = Math.floor((Date.parse(str2) - Date.parse(str1)) / 86400000);

您将得到不同的天数(如果其中一个或两个都无法解析,则为NaN)。解析日期给出了以毫秒为单位的结果,如果要以天为单位,则必须除以24 * 60 * 60 * 1000

如果你想用天、小时、分钟、秒和毫秒来划分:

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

以下是我对James版本的重构版本:

function mydiff(date1,date2,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
date1 = new Date(date1);
date2 = new Date(date2);
var timediff = date2 - date1;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years": return date2.getFullYear() - date1.getFullYear();
case "months": return (
( date2.getFullYear() * 12 + date2.getMonth() )
-
( date1.getFullYear() * 12 + date1.getMonth() )
);
case "weeks"  : return Math.floor(timediff / week);
case "days"   : return Math.floor(timediff / day);
case "hours"  : return Math.floor(timediff / hour);
case "minutes": return Math.floor(timediff / minute);
case "seconds": return Math.floor(timediff / second);
default: return undefined;
}
}

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

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

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

虽然Math.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小时,但UTC中的一天总是24小时。上面所示的daysBetween方法利用了这一事实,它首先调用treatAsUTC将本地时间调整为午夜UTC,然后再进行减法和除法。

1. JavaScript忽略闰秒。

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

diff days 2012-12-31 23:002013-01-01 01:00应该等于1。(2小时) diff days 2012-12-31 01:002013-01-01 23:00应该等于1。(46小时)< / p >

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

我建议使用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

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

Date.prototype.days = function(to) {
return Math.abs(Math.floor(to.getTime() / (3600 * 24 * 1000)) - Math.floor(this.getTime() / (3600 * 24 * 1000)))
}




console.log(new Date('2014/05/20').days(new Date('2014/05/23'))); // 3 days


console.log(new Date('2014/05/23').days(new Date('2014/05/20'))); // 3 days

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

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


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


return dayCount;
}

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

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

使用Moment.js

var future = moment('05/02/2015');
var start = moment('04/23/2015');
var d = future.diff(start, 'days'); // 9
console.log(d);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

我在Angular中也遇到了同样的问题。我复制了一份,否则他会覆盖第一次约会。两个日期的时间都必须为00:00:00(显然)

 /*
* Deze functie gebruiken we om het aantal dagen te bereken van een booking.
* */
$scope.berekenDagen = function ()
{
$scope.booking.aantalDagen=0;


/*De loper is gelijk aan de startdag van je reservatie.
* De copy is nodig anders overschijft angular de booking.van.
* */
var loper = angular.copy($scope.booking.van);


/*Zolang de reservatie beschikbaar is, doorloop de weekdagen van je start tot einddatum.*/
while (loper < $scope.booking.tot) {
/*Tel een dag op bij je loper.*/
loper.setDate(loper.getDate() + 1);
$scope.booking.aantalDagen++;
}


/*Start datum telt natuurlijk ook mee*/
$scope.booking.aantalDagen++;
$scope.infomsg +=" aantal dagen: "+$scope.booking.aantalDagen;
};
   function validateDate() {
// get dates from input fields
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
var sdate = startDate.split("-");
var edate = endDate.split("-");
var diffd = (edate[2] - sdate[2]) + 1;
var leap = [ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
var nonleap = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
if (sdate[0] > edate[0]) {
alert("Please enter End Date Year greater than Start Date Year");
document.getElementById("endDate").value = "";
diffd = "";
} else if (sdate[1] > edate[1]) {
alert("Please enter End Date month greater than Start Date month");
document.getElementById("endDate").value = "";
diffd = "";
} else if (sdate[2] > edate[2]) {
alert("Please enter End Date greater than Start Date");
document.getElementById("endDate").value = "";
diffd = "";
} else {
if (sdate[0] / 4 == 0) {
while (sdate[1] < edate[1]) {
diffd = diffd + leap[sdate[1]++];
}
} else {
while (sdate[1] < edate[1]) {
diffd = diffd + nonleap[sdate[1]++];
}
}
document.getElementById("numberOfDays").value = diffd;
}
}

如果你有两个unix时间戳,你可以使用这个函数(为了清晰起见,写得更详细一点):

// Calculate number of days between two unix timestamps
// ------------------------------------------------------------
var daysBetween = function(timeStampA, timeStampB) {
var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
var firstDate = new Date(timeStampA * 1000);
var secondDate = new Date(timeStampB * 1000);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
return diffDays;
};

例子:

daysBetween(1096580303, 1308713220); // 2455

要计算两个给定日期之间的天数,可以使用以下代码。我在这里使用的日期是2016年1月1日和2016年12月31日

var day_start = new Date("Jan 01 2016");
var day_end = new Date("Dec 31 2016");
var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24);
document.getElementById("demo").innerHTML = Math.round(total_days);
<h3>DAYS BETWEEN GIVEN DATES</h3>
<p id="demo"></p>

使用以下公式可以计算出两个不同TZs的休止日期之间的完整证明天数差:

var start = new Date('10/3/2015');
var end = new Date('11/2/2015');
var days = (end - start) / 1000 / 60 / 60 / 24;
console.log(days);
// actually its 30 ; but due to daylight savings will show 31.0xxx
// which you need to offset as below
days = days - (end.getTimezoneOffset() - start.getTimezoneOffset()) / (60 * 24);
console.log(days);

我使用下面的代码来试验新闻帖子的发布日期功能。我根据发布日期和当前日期计算分钟、小时、天或年。

var startDate= new Date("Mon Jan 01 2007 11:00:00");
var endDate  =new Date("Tue Jan 02 2007 12:50:00");
var timeStart = startDate.getTime();
var timeEnd = endDate.getTime();
var yearStart = startDate.getFullYear();
var yearEnd   = endDate.getFullYear();
if(yearStart == yearEnd)
{
var hourDiff = timeEnd - timeStart;
var secDiff = hourDiff / 1000;
var minDiff = hourDiff / 60 / 1000;
var hDiff = hourDiff / 3600 / 1000;
var myObj = {};
myObj.hours = Math.floor(hDiff);
myObj.minutes = minDiff
if(myObj.hours >= 24)
{
console.log(Math.floor(myObj.hours/24) + "day(s) ago")
}
else if(myObj.hours>0)
{
console.log(myObj.hours +"hour(s) ago")
}
else
{
console.log(Math.abs(myObj.minutes) +"minute(s) ago")
}
}
else
{
var yearDiff = yearEnd - yearStart;
console.log( yearDiff +" year(s) ago");
}

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

DebugSnippet .

使用毫秒时要小心。

date.getTime ()返回毫秒,执行以毫秒为单位的数学运算需要包含

  • 日光节约时间(DST)
  • 检查两个日期的时间是否相同(小时,分钟,秒,毫秒)
  • 请确定需要哪些天数差异:2016年9月19日- 2016年9月29日= 1天或2天的差异?
上面评论中的例子是我迄今为止找到的最佳解决方案 # EYZ0。但是如果你想计算所有涉及的天数,则使用+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;
var start= $("#firstDate").datepicker("getDate");
var end= $("#SecondDate").datepicker("getDate");
var days = (end- start) / (1000 * 60 * 60 * 24);
alert(Math.round(days));

jsfiddle示例:)

function timeDifference(date1, date2) {
var oneDay = 24 * 60 * 60; // hours*minutes*seconds
var oneHour = 60 * 60; // minutes*seconds
var oneMinute = 60; // 60 seconds
var firstDate = date1.getTime(); // convert to milliseconds
var secondDate = date2.getTime(); // convert to milliseconds
var seconds = Math.round(Math.abs(firstDate - secondDate) / 1000); //calculate the diffrence in seconds
// the difference object
var difference = {
"days": 0,
"hours": 0,
"minutes": 0,
"seconds": 0,
}
//calculate all the days and substract it from the total
while (seconds >= oneDay) {
difference.days++;
seconds -= oneDay;
}
//calculate all the remaining hours then substract it from the total
while (seconds >= oneHour) {
difference.hours++;
seconds -= oneHour;
}
//calculate all the remaining minutes then substract it from the total
while (seconds >= oneMinute) {
difference.minutes++;
seconds -= oneMinute;
}
//the remaining seconds :
difference.seconds = seconds;
//return the difference object
return difference;
}
console.log(timeDifference(new Date(2017,0,1,0,0,0),new Date()));

function formatDate(seconds, dictionary) {
var foo = new Date;
var unixtime_ms = foo.getTime();
var unixtime = parseInt(unixtime_ms / 1000);
var diff = unixtime - seconds;
var display_date;
if (diff <= 0) {
display_date = dictionary.now;
} else if (diff < 60) {
if (diff == 1) {
display_date = diff + ' ' + dictionary.second;
} else {
display_date = diff + ' ' + dictionary.seconds;
}
} else if (diff < 3540) {
diff = Math.round(diff / 60);
if (diff == 1) {
display_date = diff + ' ' + dictionary.minute;
} else {
display_date = diff + ' ' + dictionary.minutes;
}
} else if (diff < 82800) {
diff = Math.round(diff / 3600);
if (diff == 1) {
display_date = diff + ' ' + dictionary.hour;
} else {
display_date = diff + ' ' + dictionary.hours;
}
} else {
diff = Math.round(diff / 86400);
if (diff == 1) {
display_date = diff + ' ' + dictionary.day;
} else {
display_date = diff + ' ' + dictionary.days;
}
}
return display_date;
}

您可以使用UnderscoreJS来格式化和计算差异。

# EYZ0 # EYZ1

 var startDate = moment("2016-08-29T23:35:01");
var endDate = moment("2016-08-30T23:35:01");
  



console.log(startDate);
console.log(endDate);


var resultHours = endDate.diff(startDate, 'hours', true);


document.body.innerHTML = "";
document.body.appendChild(document.createTextNode(resultHours));
body { white-space: pre; font-family: monospace; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>

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

计算两个日期之间天数的简单方法是去掉它们的时间分量,即将小时、分钟、秒和毫秒设置为0,然后减去它们的时间,用一天的毫秒值来计算。

var firstDate= new Date(firstDate.setHours(0,0,0,0));
var secondDate= new Date(secondDate.setHours(0,0,0,0));
var timeDiff = firstDate.getTime() - secondDate.getTime();
var diffDays =timeDiff / (1000 * 3600 * 24);

更好的解决方案

忽略时间部分

如果两个日期相同,则返回0。

function dayDiff(firstDate, secondDate) {
firstDate = new Date(firstDate);
secondDate = new Date(secondDate);
if (!isNaN(firstDate) && !isNaN(secondDate)) {
firstDate.setHours(0, 0, 0, 0); //ignore time part
secondDate.setHours(0, 0, 0, 0); //ignore time part
var dayDiff = secondDate - firstDate;
dayDiff = dayDiff / 86400000; // divide by milisec in one day
console.log(dayDiff);
} else {
console.log("Enter valid date.");
}
}


$(document).ready(function() {
$('input[type=datetime]').datepicker({
dateFormat: "mm/dd/yy",
changeMonth: true,
changeYear: true
});
$("#button").click(function() {
dayDiff($('#first').val(), $('#second').val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>


<input type="datetime" id="first" value="12/28/2016" />
<input type="datetime" id="second" value="12/28/2017" />
<input type="button" id="button" value="Calculate">

这个答案,基于另一个答案(链接在末尾),是关于两个日期之间的差异 你可以看到它是如何工作的,因为它很简单,它还包括将差异分割为

. {/p> .

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

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

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

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).
此外,我可以使用相同的过程获得更长的时间单位,例如:
- (whole) 分钟,将除以60,并将结果更改为一个整数,
小时,将分钟除以60,并将结果更改为整数 我创建了一个函数来完成将差值分割为
的过程 整个时间单位,命名为split_to_whole_units,这个演示:

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

这个答案是基于这另一个

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

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

本机JS

步骤:

  1. 设定开始日期
  2. 设定结束日期
  3. 计算的区别
  4. 将毫秒转换为天
const diffInMs   = new Date(endDate) - new Date(startDate)
const diffInDays = diffInMs / (1000 * 60 * 60 * 24);

备注:

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

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


使用图书馆

——Date-fns

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

文档:# EYZ0

——国际光子

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

文档:# EYZ0

——Moment.js

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

文档:# EYZ0


RunKit示例

我只有两个以毫秒为单位的时间戳,所以我必须用moment.js做一些额外的步骤来获得天数。

const getDaysDiff = (fromTimestamp, toTimestamp) => {
// set timezone offset with utcOffset if needed
let fromDate = moment(fromTimestamp).utcOffset(8);
let toDate = moment(toTimestamp).utcOffset(8);
// get the start moment of the day
fromDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
toDate.set({'hour':0, 'minute': 0, 'second': 0, 'millisecond': 0});
let diffDays = toDate.diff(fromDate, 'days');


return diffDays;
}


getDaysDiff(1528889400000, 1528944180000)// 1

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

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

查询将自动生成一个列CountDays

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

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

我还建议使用<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>

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

在这种情况下使用moment会容易得多,你可以试试这个:

    let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days');

它会给你一个整数值,比如1、2、5、0等,所以你可以很容易地使用条件检查,比如:

if(days < 1) {

此外,还有一件事是你可以得到更准确的时间差结果(以小数形式,如1.2,1.5,0.7等),使用以下语法得到这种结果:

let days = moment(yourFirstDateString).diff(moment(yourSecondDateString), 'days', true);

如果你有任何进一步的疑问,请告诉我

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

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

一行代码和小代码

const diff=(e,t)=>Math.floor((new Date(e).getTime()-new Date(t).getTime())/1000*60*60*24);


// or


const diff=(e,t)=>Math.floor((new Date(e)-new Date(t))/864e5);


// or


const diff=(a,b)=>(new Date(a)-new Date(b))/864e5|0;


// use
diff('1/1/2001', '1/1/2000')

为打印稿

const diff = (from: string, to: string) => Math.floor((new Date(from).getTime() - new Date(to).getTime()) / 86400000);

我最近也有同样的问题,因为我来自Java世界,所以我立即开始搜索JavaScript的JSR 310实现。JSR 310是Java的日期和时间API (Java 8的标准版本)。我认为这个API设计得很好。

幸运的是,有一个Javascript的直接端口,称为< >强js-joda < / >强

首先,在<head>中包含js-joda:

<script
src="https://cdnjs.cloudflare.com/ajax/libs/js-joda/1.11.0/js-joda.min.js"
integrity="sha512-piLlO+P2f15QHjUv0DEXBd4HvkL03Orhi30Ur5n1E4Gk2LE4BxiBAP/AD+dxhxpW66DiMY2wZqQWHAuS53RFDg=="
crossorigin="anonymous"></script>

然后简单地这样做:

let date1 = JSJoda.LocalDate.of(2020, 12, 1);
let date2 = JSJoda.LocalDate.of(2021, 1, 1);
let daysBetween = JSJoda.ChronoUnit.DAYS.between(date1, date2);

现在daysBetween包含间隔的天数。注意,结束日期是独家

试试这个

let today = new Date().toISOString().slice(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  );

 // 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 :) ");

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