如果我有两个日期,我如何使用JavaScript在几分钟内获得两个日期之间的差异?
JavaScript - 获取两个日期之间的分钟数
IT技术
javascript
datetime
2021-02-10 19:28:53
6个回答
您可以查看此代码:
var today = new Date();
var Christmas = new Date(today.getFullYear() + "-12-25");
var diffMs = (Christmas - today); // milliseconds between now & Christmas
var diffDays = Math.floor(diffMs / 86400000); // days
var diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
alert(diffDays + " days, " + diffHrs + " hours, " + diffMins + " minutes until Christmas =)");
或者var diffMins = Math.floor((...
如果您不想舍入分钟,则丢弃秒数。
减去 2 个 Date 对象会给你以毫秒为单位的差异,例如:
var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));
Math.abs
用于能够使用绝对差异(因此new Date('2011/10/09 00:00') - new Date('2011/10/09 12:00')
给出相同的结果)。
结果除以 1000 就是秒数。除以 60 就是分钟数。要四舍五入到整分钟,请使用Math.floor
或Math.ceil
:
var minutes = Math.floor((diff/1000)/60);
在这个例子中,结果将是 720
var startTime = new Date('2012/10/09 12:00');
var endTime = new Date('2013/10/09 12:00');
var difference = endTime.getTime() - startTime.getTime(); // This will give difference in milliseconds
var resultInMinutes = Math.round(difference / 60000);
执行此计算的简单函数:
function getMinutesBetweenDates(startDate, endDate) {
var diff = endDate.getTime() - startDate.getTime();
return (diff / 60000);
}
这应该以分钟为单位显示两个日期之间的差异。在浏览器中尝试:
const currDate = new Date('Tue Feb 13 2018 13:04:58 GMT+0200 (EET)')
const oldDate = new Date('Tue Feb 13 2018 12:00:58 GMT+0200 (EET)')
(currDate - oldDate) / 60000 // 64
其它你可能感兴趣的问题