我想用天、小时、分钟、秒、毫秒、纳秒来计算日期差异。我该怎么做呢?
当前回答
像“差几天”这样的表达从来不像看起来那么简单。如果你有以下日期:
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.
e.g. getDaysBetweenDates( 22-Jul-2011, 29-jul-2011) => 7.
If want inclusive dates (e.g. leave from 1/1/2011 to 30/1/2011),
use date prior to start date (i.e. 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. ** ** e.g. 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>'); });
其他回答
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
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.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")
基于javascript运行时原型实现,您可以使用简单的算术减去日期如下所示
var sep = new Date(2020, 07, 31, 23, 59, 59);
var today = new Date();
var diffD = Math.floor((sep - today) / (1000 * 60 * 60 * 24));
console.log('Day Diff: '+diffD);
差值返回以毫秒为单位的答案,然后你必须通过除法转换它:
按1000换算成秒 通过1000×60转换为分钟 通过1000×60×60转换为小时 通过1000×60×60×24转换为日
<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>