如果我有两个日期,如何使用JavaScript在分钟内得到两个日期之间的差异?
当前回答
这应该以分钟为单位显示两个日期之间的差异。在浏览器中试试:
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
其他回答
它很容易工作:
var endTime = $("#ExamEndTime").val();
var startTime = $("#ExamStartTime").val();
//create date format
var timeStart = new Date("01/01/2007 " + startTime);
var timeEnd = new Date("01/01/2007 " + endTime);
var msInMinute = 60 * 1000;
var difference = Math.round(Math.abs(timeEnd - timeStart) / msInMinute);
$("#txtCalculate").val(difference);
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);
这个问题用moment.js很容易解决,就像下面这个例子:
var差异= mostDate。鼩(minorDate,“分钟”);
第二个参数可以更改为其他参数,请参阅moment.js文档。
例如:“天”、“小时”、“分钟”等。
http://momentjs.com/docs/
moment.js的CDN在这里:
https://cdnjs.com/libraries/moment.js
谢谢。
编辑:
mostDate和minorDate应该是moment类型。
编辑2:
对于那些在2020年以后阅读我的答案的人来说,momentjs现在是一个遗留项目。
如果你还在寻找一个知名的库来做这项工作,我会推荐date-fns。
// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
new Date(2014, 6, 2, 12, 20, 0),
new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12
这是可行的
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