【发布时间】:2011-10-10 07:41:37
【问题描述】:
如果我有两个日期,我如何使用JavaScript 来获得两个日期之间的分钟差?
【问题讨论】:
-
它们是日期对象还是字符串?请举例说明情况
标签: javascript datetime
如果我有两个日期,我如何使用JavaScript 来获得两个日期之间的分钟差?
【问题讨论】:
标签: javascript datetime
您可以签出此代码:
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((... 如果您不想四舍五入,则丢弃秒数。
【讨论】:
Math.round(((diffMs % 86400000) % 3600000) / 60000); 时差大于 60 分钟时不起作用
减去两个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。
[edit 2022] 使用上述知识,添加了更完整的演示 sn-p。
untilXMas();
function difference2Parts(milliseconds) {
const secs = Math.floor(Math.abs(milliseconds) / 1000);
const mins = Math.floor(secs / 60);
const hours = Math.floor(mins / 60);
const days = Math.floor(hours / 24);
const millisecs = Math.floor(Math.abs(milliseconds)) % 1000;
const multiple = (term, n) => n !== 1 ? `${n} ${term}s` : `1 ${term}`;
return {
days: days,
hours: hours % 24,
hoursTotal: hours,
minutesTotal: mins,
minutes: mins % 60,
seconds: secs % 60,
secondsTotal: secs,
milliSeconds: millisecs,
get diffStr() {
return `${multiple(`day`, this.days)}, ${
multiple(`hour`, this.hours)}, ${
multiple(`minute`, this.minutes)} and ${
multiple(`second`, this.seconds)}`;
},
get diffStrMs() {
return `${this.diffStr.replace(` and`, `, `)} and ${
multiple(`millisecond`, this.milliSeconds)}`;
},
};
}
function untilXMas() {
const nextChristmas = new Date(Date.UTC(new Date().getFullYear(), 11, 25));
const report = document.querySelector(`#nextXMas`);
const diff = () => {
const diffs = difference2Parts(nextChristmas - new Date());
report.innerHTML = `Awaiting next XMas ? (${
diffs.diffStrMs.replace(/(\d+)/g, a => `<b>${a}</b>`)})<br>
<br>In other words, until next XMas lasts…<br>
In minutes: <b>${diffs.minutesTotal}</b><br>In hours: <b>${
diffs.hoursTotal}</b><br>In seconds: <b>${diffs.secondsTotal}</b>`;
setTimeout(diff, 200);
};
return diff();
}
body {
font: 14px/17px normal verdana, arial;
margin: 1rem;
}
<div id="nextXMas"></div>
【讨论】:
new Date(string) 与 ISO-8601 格式字符串以外的格式一起使用。请参阅Why does Date.parse give incorrect results?,或仅使用数字(例如,new Date(2011, 9, 9, 12, 0, 0);请记住月份是从 0 开始的)。
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);
【讨论】:
new Date(string) 与 ISO-8601 格式字符串以外的格式一起使用。请参阅Why does Date.parse give incorrect results?,或仅使用数字(例如,new Date(2011, 9, 9, 12, 0, 0);请记住月份是从 0 开始的)。
执行此计算的简单函数:
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
【讨论】:
(currDate.getTime() - oldDate.getTime()) / 60000
这个问题用moment.js很容易解决,比如这个例子:
var difference = mostDate.diff(minorDate, "minutes");
第二个参数可以改成其他参数,见moment.js文档。
例如:“天”、“小时”、“分钟”等
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
【讨论】:
对于那些喜欢处理小数字的人
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);
【讨论】:
你可以这样做:
difference of dates(差异以毫秒为单位)milliseconds 转换为minutes 即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);
【讨论】:
这是我在节点中解决类似问题时遇到的一些乐趣。
function formatTimeDiff(date1, date2) {
return Array(3)
.fill([3600, date1.getTime() - date2.getTime()])
.map((v, i, a) => {
a[i+1] = [a[i][0]/60, ((v[1] / (v[0] * 1000)) % 1) * (v[0] * 1000)];
return `0${Math.floor(v[1] / (v[0] * 1000))}`.slice(-2);
}).join(':');
}
const millis = 1000;
const utcEnd = new Date(1541424202 * millis);
const utcStart = new Date(1541389579 * millis);
const utcDiff = formatTimeDiff(utcEnd, utcStart);
console.log(`Dates:
Start : ${utcStart}
Stop : ${utcEnd}
Elapsed : ${utcDiff}
`);
/*
Outputs:
Dates:
Start : Mon Nov 05 2018 03:46:19 GMT+0000 (UTC)
Stop : Mon Nov 05 2018 13:23:22 GMT+0000 (UTC)
Elapsed : 09:37:02
*/
您可以在https://repl.it/@GioCirque/TimeSpan-Formatting看到它的实际应用
【讨论】:
以下代码对我有用,
function timeDiffCalc(dateNow,dateFuture) {
var newYear1 = new Date(dateNow);
var newYear2 = new Date(dateFuture);
var dif = (newYear2 - newYear1);
var dif = Math.round((dif/1000)/60);
console.log(dif);
}
【讨论】:
这会起作用
duration = moment.duration(moment(end_time).diff(moment(start_time)))
【讨论】: