Joh*_*ohn 132 javascript datetime
如果我有两个日期,我如何使用JavaScript在几分钟内获得两个日期之间的差异?
Dar*_*rov 179
你可以签出这个代码:
var today = new Date();
var Christmas = new Date("12-25-2012");
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 2009 =)");Run Code Online (Sandbox Code Playgroud)
或者var diffMins = Math.floor((...如果你不想要几分钟就丢弃秒.
Koo*_*Inc 148
减去2个Date对象可以得到毫秒差异,例如:
var diff = Math.abs(new Date('2011/10/09 12:00') - new Date('2011/10/09 00:00'));
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
在此示例中,结果将为720
MrG*_*rki 47
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);
Run Code Online (Sandbox Code Playgroud)
All*_*ice 42
执行此计算的简单函数:
function getMinutesBetweenDates(startDate, endDate) {
var diff = endDate.getTime() - startDate.getTime();
return (diff / 60000);
}
Run Code Online (Sandbox Code Playgroud)
Pur*_*lex 19
这应该以分钟为单位显示两个日期之间的差异.
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.0026
Run Code Online (Sandbox Code Playgroud)
Ric*_*ick 10
对于那些喜欢小数字的人
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);
Run Code Online (Sandbox Code Playgroud)
使用moment.js可以轻松解决此问题,如下例所示:
var difference = mostDate.diff(minorDate, "minutes");
可以为其他参数更改第二个参数,请参阅moment.js文档.
例如:"天","小时","分钟"等.
适用于moment.js的CDN可在此处获得:
https://cdnjs.com/libraries/moment.js
谢谢.
编辑:
mostDate和minorDate应该是片刻类型.
小智 7
您可以执行以下操作:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
157094 次 |
| 最近记录: |