如何获得JavaScript中两个date之间的天数?

如何获得JavaScript中两个date之间的天数? 例如,在input框中给出两个date:

<input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/> <script> alert(datediff("day", first, second)); // what goes here? </script> 
 function parseDate(str) { var mdy = str.split('/'); return new Date(mdy[2], mdy[0]-1, mdy[1]); } function daydiff(first, second) { return Math.round((second-first)/(1000*60*60*24)); } console.log(daydiff(parseDate($('#first').val()), parseDate($('#second').val()))); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/> 

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

尽pipeMath.round返回正确的结果,但我认为它有点笨重。 相反,当DST开始或结束时,通过明确loggingUTC偏移量的变化,我们可以使用精确算术:

 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计算是棘手的,因为Date对象存储在UTC内部的时间,而不是本地时间。 例如,3/10/2013 12:00 AM太平洋标准时间(UTC-08:00)的存储时间为2013年3月10日8:00 UTC,3/11/2013 12:00 AM太平洋夏令时( UTC-07:00)存储为3/11/2013上午7:00 UTC。 在这一天,午夜到当地时间午夜UTC只有23个小时!

尽pipe当地时间的一天可能多于或less于24小时,但UTC的一天总是24小时。 1上面显示的daysBetween方法利用了这个事实,首先调用treatAsUTC来调整两个本地时间到UTC的午夜,然后再进行减法和除法。

1. JavaScript忽略闰秒。

最简单的方法来获得两个date之间的差异:

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

你得到不同的日子(或NaN,如果一个或两个不能被parsing)。 parsingdate以毫秒为单位给出结果,并且在白天得到结果,必须将结果除以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; } } 

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

我会继续前进, 抓住这个小工具 ,在这里你可以find适合你的function。 这是一个简短的例子:

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

使用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="ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script> 

JS中的date值是date时间值。

所以,直接的date计算是不一致的:

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

例如我们需要转换de第二date:

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

该方法可能会在两个date截断工厂:

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

我认为解决scheme是不正确的100%我会使用ceil而不是floor ,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) }; } 

要计算2个给定date之间的天数,您可以使用以下代码。我在这里使用的date是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> 

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

我发现这个问题的时候,我想在两个date做一些计算,但date有小时和分钟的价值,我修改@迈克尔刘的答案,以符合我的要求,并通过了我的testing。

差天2012-12-31 23:002013-01-01 01:00应该等于1.(2小时)差天2012-12-31 01:002013-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); } 

可以使用下面的公式计算在不同TZ中rest的两个date之间的全天certificate差异:

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

最好使用UTC时间去除DST,Math.ceil,Math.floor等:

 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是以毫秒为单位的一天。

 var start= $("#firstDate").datepicker("getDate"); var end= $("#SecondDate").datepicker("getDate"); var days = (end- start) / (1000 * 60 * 60 * 24); alert(Math.round(days)); 

jsfiddle例子:)

使用毫秒时要小心。

date.getTime()返回毫秒, math运算以毫秒为单位需要包含

  • 夏令时(DST)
  • 检查两个date是否具有相同的时间(小时,分钟,秒,毫秒)
  • 请确定需要差异化date的行为:2016年9月19日 – 2016年9月29日=差额为1天或2天?

上面评论的例子是我迄今为止发现的最好的解决schemehttps://stackoverflow.com/a/11252167/2091095 。 但是,如果您想要统计所有涉及的天数,请使用+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; 
 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())); 
 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 

我在Angular中遇到了同样的问题。 我做的副本,因为否则他会覆盖第一个date。 这两个date必须有时间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; }; 

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

我使用下面的代码来实验新闻发布的发布datefunction。我根据发布date和当前date计算分钟或小时或日或年。

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

如果你想有dateDateArray试试这个:

 <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

这可能不是最优雅的解决scheme,但我认为,似乎用相对简单的代码来回答这个问题。 你不能使用这样的东西:

 function dayDiff(startdate, enddate) { var dayCount = 0; while(enddate >= startdate) { dayCount++; startdate.setDate(startdate.getDate() + 1); } return dayCount; } 

这是假设您将date对象作为parameter passing。

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

如果你想要一个类似于moment.js的解决scheme,而没有库的开销,你可以使用我写的这个组件 。

为了获得日子:

 var date1 = new Date('January 24, 1984 09:41:00'); var date2 = new Date('June 29, 2007 18:45:10'); var numDays = dateDiff(date1, date2, 'days'); 

除了计算两个date之间的天数之外,还可以计算所有其他标准时间单位(秒,小时,周,月等)。

要使用dateDiff()方法,您可以导入组件。

计算两个date之间的天数的简单方法是删除它们的时间分量,即将小时,分钟,秒和毫秒设置为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); 

一个更好的解决scheme

忽略时间部分

如果两个date相同,它将返回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"> 
  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; } } 

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

演示 https://jsfiddle.net/sumitridhal/8sv94msp/

  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="ajax/libs/moment.js/2.5.1/moment.min.js"></script> 

其他答案的小书签版本,提示你两个date:

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

这是最初发布在https://stackoverflow.com/a/1968175/3787376的答案。;
该方法包括一个有用的function,我创build的差异分为时间单位。

通过使用Date对象及其毫秒值,可以计算差异:

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

您可以通过将毫秒除以1000来获得秒数(以整数/整数),将其转换为秒,然后将结果转换为整数(这将删除表示毫秒的小数部分):

 var seconds = parseInt((ba)/1000); 

然后,您可以通过将seconds除以60并将其转换为整数来获得整个minutes ,然后将minutes除以60并将其转换为整数,然后以相同的方式将其转换为更长的时间单位。 由此,可以创build下部单元的值和下部单元的值中的最大时间单位的函数:

 function get_whole_values(base_value, time_fractions) { time_data = [base_value]; for (i = 0; i < time_fractions.length; i++) { time_data.push(parseInt(time_data[i]/time_fractions[i])); time_data[i] = time_data[i] % time_fractions[i]; }; return time_data; }; // Input variables below: starting value of 72000 milliseconds, time fractions are // 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute). console.log(get_whole_values(72000, [1000, 60])); // -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute. 

上面为第二个Date对象提供的input选项使用以下格式:

 new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>); 

正如本解决scheme最初提到的注释,除非需要创builddate,否则不需要提供所有这些值。