如何在JavaScript中计算日期差异

我想计算天数,小时,分钟,秒,毫秒,纳秒的日期差异,我该怎么做呢? 请建议。

假设你有两个Date对象 ,你可以减去它们来得到毫秒的差异:

 var difference = date2 - date1; 

从那里,你可以使用简单的算术来导出其他值。

 var DateDiff = { inDays: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/(24*3600*1000)); }, inWeeks: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime(); return parseInt((t2-t1)/(24*3600*1000*7)); }, inMonths: function(d1, d2) { var d1Y = d1.getFullYear(); var d2Y = d2.getFullYear(); var d1M = d1.getMonth(); var d2M = d2.getMonth(); return (d2M+12*d2Y)-(d1M+12*d1Y); }, inYears: function(d1, d2) { return d2.getFullYear()-d1.getFullYear(); } } var dString = "May, 20, 1984"; var d1 = new Date(dString); var d2 = new Date(); document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2)); document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2)); document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2)); document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2)); 

取自这里的代码示例。

另一个解决方案是将差异转换为新的Date对象,并获取该日期的年份(从1970年差异),月,日等。

 var date1 = new Date(2010, 6, 17); var date2 = new Date(2013, 12, 18); var diff = new Date(date2.getTime() - date1.getTime()); // diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST) console.log(diff.getUTCFullYear() - 1970); // Gives difference as year // 3 console.log(diff.getUTCMonth()); // Gives month count of difference // 6 console.log(diff.getUTCDate() - 1); // Gives day count of difference // 4 

所以区别就像“3年零6个月零4天”。 如果你想在人类可读的风格上有所作为,那可以帮助你。

像“天差异”这样的表达从来不像看起来那么简单。 如果您有以下日期:

 d1: 2011-10-15 23:59:00 d1: 2011-10-16 00:01:00 

时间差是2分钟,“天差”是1还是0? 类似的问题出现在几个月,几年或任何表达的差异,因为年,月和日有不同的长度和不同的时间(例如,夏令时开始的时间比平常短1小时,比当天短2小时它结束)。

这是一个忽略时间差异的函数,即上述日期返回1。

 /* Get the number of days between two dates - not inclusive. "between" does not include the start date, so days between Thursday and Friday is one, Thursday to Saturday is two, and so on. Between Friday and the following Friday is 7. eg getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7. If want inclusive dates (eg leave from 1/1/2011 to 30/1/2011), use date prior to start date (ie 31/12/2010 to 30/1/2011). Only calculates whole days. Assumes d0 <= d1 */ function getDaysBetweenDates(d0, d1) { var msPerDay = 8.64e7; // Copy dates so don't mess them up var x0 = new Date(d0); var x1 = new Date(d1); // Set to noon - avoid DST errors x0.setHours(12,0,0); x1.setHours(12,0,0); // Round to remove daylight saving errors return Math.round( (x1 - x0) / msPerDay ); } 

这可以更简洁:

 /* Return number of days between d0 and d1. ** Returns positive if d0 < d1, otherwise negative. ** ** eg between 2000-02-28 and 2001-02-28 there are 366 days ** between 2015-12-28 and 2015-12-29 there is 1 day ** between 2015-12-28 23:59:59 and 2015-12-29 00:00:01 there is 1 day ** between 2015-12-28 00:00:01 and 2015-12-28 23:59:59 there are 0 days ** ** @param {Date} d0 - start date ** @param {Date} d1 - end date ** @returns {number} - whole number of days between d0 and d1 ** */ function daysDifference(d0, d1) { var diff = new Date(+d1).setHours(12) - new Date(+d0).setHours(12); return Math.round(diff/8.64e7); } // Simple formatter function formatDate(date){ return [date.getFullYear(),('0'+(date.getMonth()+1)).slice(-2),('0'+date.getDate()).slice(-2)].join('-'); } // Examples [[new Date(2000,1,28), new Date(2001,1,28)], // Leap year [new Date(2001,1,28), new Date(2002,1,28)], // Not leap year [new Date(2017,0,1), new Date(2017,1,1)] ].forEach(function(dates) { document.write('From ' + formatDate(dates[0]) + ' to ' + formatDate(dates[1]) + ' is ' + daysDifference(dates[0],dates[1]) + ' days<br>'); }); 
 <html lang="en"> <head> <script> function getDateDiff(time1, time2) { var str1= time1.split('/'); var str2= time2.split('/'); // yyyy , mm , dd var t1 = new Date(str1[2], str1[0]-1, str1[1]); var t2 = new Date(str2[2], str2[0]-1, str2[1]); var diffMS = t1 - t2; console.log(diffMS + ' ms'); var diffS = diffMS / 1000; console.log(diffS + ' '); var diffM = diffS / 60; console.log(diffM + ' minutes'); var diffH = diffM / 60; console.log(diffH + ' hours'); var diffD = diffH / 24; console.log(diffD + ' days'); alert(diffD); } //alert(getDateDiff('10/18/2013','10/14/2013')); </script> </head> <body> <input type="button" onclick="getDateDiff('10/18/2013','10/14/2013')" value="clickHere()" /> </body> </html> 

使用Moment.js进行所有与JavaScript相关的日期 – 时间计算

回答你的问题是:

 var a = moment([2007, 0, 29]); var b = moment([2007, 0, 28]); a.diff(b) // 86400000 

完整的细节可以在这里找到

 function DateDiff(date1, date2) { date1.setHours(0); date1.setMinutes(0, 0, 0); date2.setHours(0); date2.setMinutes(0, 0, 0); var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value } 
 var d1=new Date(2011,0,1); // jan,1 2011 var d2=new Date(); // now var diff=d2-d1,sign=diff<0?-1:1,milliseconds,seconds,minutes,hours,days; diff/=sign; // or diff=Math.abs(diff); diff=(diff-(milliseconds=diff%1000))/1000; diff=(diff-(seconds=diff%60))/60; diff=(diff-(minutes=diff%60))/60; days=(diff-(hours=diff%24))/24; console.info(sign===1?"Elapsed: ":"Remains: ", days+" days, ", hours+" hours, ", minutes+" minutes, ", seconds+" seconds, ", milliseconds+" milliseconds."); 

随着时间的推移,这很简单:

 moment("2016-04-08").fromNow(); 

如果您使用的是moment.js,那么找到日期差异非常简单。

 var now = "04/09/2013 15:00:00"; var then = "04/09/2013 14:20:30"; moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss") 

对不起,平坦的毫秒计算是不可靠的感谢所有的答复,但我试过的功能很少是在1日失败。日期接近今天的日期2. 1970年的日期或3.闰年的日期。

最适合我的方法,涵盖所有情况,例如闰年,1970年接近日期,二十九岁等。

 var someday = new Date("8/1/1985"); var today = new Date(); var years = today.getFullYear() - someday.getFullYear(); // Reset someday to the current year. someday.setFullYear(today.getFullYear()); // Depending on when that day falls for this year, subtract 1. if (today < someday) { years--; } document.write("Its been " + years + " full years."); 
 function DateDiff(b, e) { let endYear = e.getFullYear(), endMonth = e.getMonth(), years = endYear - b.getFullYear(), months = endMonth - b.getMonth(), days = e.getDate() - b.getDate(); if (months < 0) { years--; months += 12; } if (days < 0) { months--; days += new Date(endYear, endMonth, 0).getDate(); } return [years, months, days]; } [years, months, days] = DateDiff( new Date("October 21, 1980", new Date("July 11, 2017"))); // 36 8 20 

你也可以使用这个很容易使用的日期操作库http://www.datejs.com/

例如:

 // Add 3 days to Today Date.today().add(3).days(); 

(与日期格式化库非常吻合)

为了简化这个,我写了一个与moment.js解决方案类似的组件 ,没有使用整个库的开销。 它也允许你跳过所有的手动算术在时间单位之间进行转换。 您可以输入两个Date对象,并以毫秒,秒,分钟,小时,天,周,月或年来查找它们之间的差异。

例如:

 var date1 = new Date('January 24, 1984 09:41:00'); var date2 = new Date('June 29, 2007 18:45:10'); dateDiff(date1, date2, 'milliseconds'); // => 739357450000 dateDiff(date1, date2, 'seconds'); // => 739357450 dateDiff(date1, date2, 'minutes'); // => 12322624 dateDiff(date1, date2, 'hours'); // => 205377 dateDiff(date1, date2, 'days'); // => 8557 dateDiff(date1, date2, 'weeks'); // => 1222 dateDiff(date1, date2, 'months'); // => 281 dateDiff(date1, date2, 'years'); // => 23 

随意导入组件以在项目中使用dateDiff()方法。