How do I get the number of days between two dates in JavaScript?
如何在javascript中获取两个日期之间的天数?例如,输入框中有两个日期:
1 2 3 4 5 | <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/> alert(datediff("day", first, second)); // what goes here? |
这里有一个快速而肮脏的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 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]); } function datediff(first, second) { // Take the difference between the dates and divide by milliseconds per day. // Round to nearest whole number to deal with DST. return Math.round((second-first)/(1000*60*60*24)); } alert(datediff(parseDate(first.value), parseDate(second.value))); |
1 2 | <input id="first" value="1/1/2000"/> <input id="second" value="1/1/2001"/> |
您应该知道,"正常"日期API(名称中没有"UTC")在用户浏览器的本地时区运行,因此通常,如果您的用户处于您不期望的时区,并且您的代码必须处理夏令时转换,您可能会遇到问题。您应该仔细阅读日期对象及其方法的文档,对于更复杂的内容,强烈考虑使用为日期操作提供更安全、更强大的API的库。
- 数字和日期MDN javascript指南
Date mdn javascript引用
此外,为了便于说明,代码段在
在撰写本文时,只有其他答案中的一个正确处理DST(夏令时)转换。以下是加利福尼亚州一个系统的结果:
1 2 3 4 5 6 7 8 9 | 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 |
虽然
1 2 3 4 5 6 7 8 9 10 11 12 | 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日期计算很困难,因为
虽然当地时间的一天可能有多于或少于24小时,但UTC中的一天总是正好24小时。1上面显示的
1。javascript忽略闰秒。
获取两个日期之间差异的最简单方法:
1 | var diff = Math.floor(( Date.parse(str2) - Date.parse(str1) ) / 86400000); |
您将得到不同的天数(如果一天或两天都无法分析,则为nan)。解析日期以毫秒为单位给出了结果,要按天计算,必须除以24*60*60*1000。
如果要除以天、小时、分钟、秒和毫秒:
1 2 3 4 5 6 7 8 9 10 11 | 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版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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; } } |
我建议使用moment.js库(http://momentjs.com/docs//displaying/difference/)。它能正确处理夏令时,而且一般来说是很好的工作。
例子:
1 2 3 4 | var start = moment("2013-11-03"); var end = moment("2013-11-04"); end.diff(start,"days") 1 |
我会继续,并抓住这个小的实用程序,在它中,你会找到这个函数为你。下面是一个简短的例子:
1 2 3 4 5 6 7 8 9 10 11 | <script type="text/javascript" src="date.js"> <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 ); |
1 2 3 4 | const startDate = '2017-11-08'; const endDate = '2017-10-01'; const timeDiff = (new Date(startDate)) - (new Date(endDate)); const days = timeDiff / (1000 * 60 * 60 * 24) |
使用Moment.js
1 2 3 4 | var future = moment('05/02/2015'); var start = moment('04/23/2015'); var d = future.diff(start, 'days'); // 9 console.log(d); |
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"> |
JS中的日期值是日期时间值。
因此,直接日期计算不一致:
1 | (2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day |
例如,我们需要转换de 2nd日期:
1 | (2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day |
该方法可以在两个日期截断工厂:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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); |
要计算两个给定日期之间的天数,可以使用以下代码。我在这里使用的日期是2016年1月1日和2016年12月31日
1 2 3 4 | 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); |
1 2 3 | DAYS BETWEEN GIVEN DATES <p id="demo"> </p> |
最好使用UTC时间来消除DST、math.ceil、math.floor等:
1 2 3 4 | 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天的差异。
可以使用以下公式计算跨越不同TZ的两个日期之间的完整证明天数差异:
1 2 3 4 5 6 7 8 | 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); |
我认为解决方案是不正确的100%我会用天花板而不是地板,轮将工作,但它不是正确的操作。
1 2 3 4 5 6 7 8 9 10 11 | 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) }; } |
当我想在两个日期上做一些计算时,我发现了这个问题,但是日期有小时和分钟值,我修改了@michael liu的答案以满足我的要求,它通过了我的测试。
1 2 3 4 5 6 7 8 9 10 | 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); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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())); |
1 2 3 4 | var start= $("#firstDate").datepicker("getDate"); var end= $("#SecondDate").datepicker("getDate"); var days = (end- start) / (1000 * 60 * 60 * 24); alert(Math.round(days)); |
jfiddle示例:)
使用来自日期选取器小部件的格式化日期怎么样?您可以使用它来转换时间戳格式的日期(从1970年1月1日起的毫秒数),然后做一个简单的减法。
这可能不是最优雅的解决方案,但我认为它似乎用一个相对简单的代码来回答这个问题。你不能用这样的东西吗?
1 2 3 4 5 6 7 8 9 10 | function dayDiff(startdate, enddate) { var dayCount = 0; while(enddate >= startdate) { dayCount++; startdate.setDate(startdate.getDate() + 1); } return dayCount; } |
这是假设您正在将日期对象作为参数传递。
使用毫秒时要小心。
date.gettime()返回毫秒,而使用毫秒进行数学运算需要包括
- 夏令时(DST)
- 检查两个日期的时间是否相同(小时、分钟、秒、毫秒)
- 确保需要什么样的天数差异行为:2016年9月19日-2016年9月29日=1或2天差异?
以上评论中的例子是迄今为止我找到的最佳解决方案https://stackoverflow.com/a/11252167/2091095。但是,如果您希望统计所有涉及的天数,请对其结果使用+1。
1 2 3 4 5 6 7 8 9 10 11 12 | 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; |
1 2 3 4 5 6 7 8 | 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 |
我使用下面的代码来实验新闻发布的发布日期功能,我根据发布日期和当前日期计算分钟、小时、天或年。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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"); } |
计算两个日期之间的天数的简单方法是删除两个时间分量,即将小时、分钟、秒和毫秒设置为0,然后减去它们的时间,并用毫秒值为一天的时间进行潜水。
1 2 3 4 | 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); |
我在角度上也有同样的问题。我抄袭是因为他会改写第一个日期。两个日期都必须有时间00:00:00(显然)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /* * 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时间戳,则可以使用此函数(为了清晰起见,稍微详细一点):
1 2 3 4 5 6 7 8 9 | // 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; }; |
例子:
1 | daysBetween(1096580303, 1308713220); // 2455 |
如果您想要一个日期数组,请尝试以下操作:
1 2 3 4 5 6 7 8 9 10 11 12 | 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; } |
调试片段
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 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; } |
更好的解决方案
Ignoring time part
如果两个日期相同,则返回0。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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()); }); }); |
1 2 3 4 5 6 7 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> <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"> <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"> |
A供款,用于1970-01-01之前和2038-01-19之后的日期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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); })(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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; } } |
您可以使用下划线来格式化和计算差异。
演示https://jsfiddle.net/sumitridhal/8sv94msp/
1 2 3 4 5 6 7 8 9 10 11 | 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)); |
1 | body { white-space: pre; font-family: monospace; } |
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"> |
这个答案基于另一个(结尾的链接),是关于两个日期之间的差异。你可以看到它是如何工作的,因为它很简单,还包括将差异分成时间单位(我所做的函数),并转换为UTC以停止时区问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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)] );} )); |
可以使用日期对象计算日期/时间差(毫秒):
1 2 3 4 5 6 | 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进行转换毫秒到秒,然后将结果更改为整数(整数)以删除毫秒(小数部分):
我创建了一个函数,用于将差异分解为整个时间单位,命名为
1 2 | console.log(split_to_whole_units(72000, [1000, 60])); // -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds. |
这个答案是基于另一个。
简单、简单、复杂。此函数将每1秒调用一次以更新时间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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.js做一些额外的步骤来计算这两天之间的时间。
28我也有同样的问题,但最好是在SQL查询上完成:
1 | DateDiff(DAY, StartValue,GETDATE()) AS CountDays |
查询将自动生成一列
我从其他答案中得到了一些启发,并使输入具有自动卫生功能。我希望这能比其他答案更有效。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | //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(date1, date2) { if (!date1 || !date2) { return 0; } return Math.round((date2.getTime() - date1.getTime()) / MS_PER_DAY); } // new Date("dateString") is browser-dependent and discouraged, so we'll write // a simple parse function for U.S. date format. (by @Miles) function parseDate(str) { if (str && str.length > 5 && str.length < 10) { let mdy = str.split('/'); return new Date(mdy[2], mdy[0]-1, mdy[1]); } return null; } function calcInputs() { let date1 = document.getElementById("date1") , date2 = document.getElementById("date2") , resultSpan = document.getElementById("result") ; if (date1 && date2 && resultSpan) { //remove non-date characters let date1Val = date1.value.replace(/[^\d\/]/g,'') , date2Val = date2.value.replace(/[^\d\/]/g,'') , result = dateDiffInDays(parseDate(date1Val), parseDate(date2Val)) ; date1.value = date1Val; date2.value = date2Val; resultSpan.innerHTML = result +" days"; } } window.onload = function() { calcInputs(); }; //some code examples console.log(dateDiffInDays(parseDate("1/15/2019"), parseDate("1/30/2019"))); console.log(dateDiffInDays(parseDate("1/15/2019"), parseDate("2/30/2019"))); console.log(dateDiffInDays(parseDate("1/15/2000"), parseDate("1/15/2019"))); |
1 2 3 | <input id="date1" type="text" value="1/1/2000" size="6" onkeyup="calcInputs();" /> <input id="date2" type="text" value="1/1/2019" size="6" onkeyup="calcInputs();"/> Result: <span id="result"></span> |
其他答案的书签版本,提示您输入两个日期:
1 2 3 4 5 6 7 8 9 | 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) ) )); })(); |