如果我有两个日期,如何使用JavaScript在分钟内得到两个日期之间的差异?


当前回答

这是可行的

duration = moment.duration(moment(end_time).diff(moment(start_time)))

其他回答

您可以进行如下操作:

获取日期的差异(以毫秒为单位) 将毫秒转换为分钟i-e ms/1000/60

代码:

let dateOne = new Date("2020-07-10");
let dateTwo = new Date("2020-07-11");

let msDifference =  dateTwo - dateOne;
let minutes = Math.floor(msDifference/1000/60);
console.log("Minutes between two dates =",minutes);

对于那些喜欢处理小数字的人

const today = new Date();
const endDate = new Date(startDate.setDate(startDate.getDate() + 7));
const days = parseInt((endDate - today) / (1000 * 60 * 60 * 24));
const hours = parseInt(Math.abs(endDate - today) / (1000 * 60 * 60) % 24);
const minutes = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000 * 60) % 60);
const seconds = parseInt(Math.abs(endDate.getTime() - today.getTime()) / (1000) % 60); 

一个简单的函数来执行这个计算:

function getMinutesBetweenDates(startDate, endDate) {
    var diff = endDate.getTime() - startDate.getTime();
    return (diff / 60000);
}

这是可行的

duration = moment.duration(moment(end_time).diff(moment(start_time)))

这应该以分钟为单位显示两个日期之间的差异。在浏览器中试试:

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