如何在 JavaScript 中计算两个日期之间的分钟数?
admin 阅读:104 2024-05-13

在本文中,您将了解如何在 JavaScript 中计算两个日期之间的分钟数。
Date 对象适用于日期和时间。日期对象是用 new Date() 创建的。 JavaScript 将使用浏览器的时区并将日期显示为全文字符串。
示例 1
在此示例中,我们使用函数来查找时间差。
function minutesDiff(dateTimeValue2, dateTimeValue1) {
var differenceValue =(dateTimeValue2.getTime() - dateTimeValue1.getTime()) / 1000;
differenceValue /= 60;
return Math.abs(Math.round(differenceValue));
}
dateTimeValue1 = new Date(2020,12,12);
console.log("The first date time value is defined as: ", dateTimeValue1)
dateTimeValue2 = new Date(2020,12,13);
console.log("The second date time value is defined as: ", dateTimeValue2)
console.log(" The difference in the two date time values in minutes is: ")
console.log(minutesDiff(dateTimeValue1, dateTimeValue2));说明
步骤 1 - 定义两个日期时间值 dateTimeValue1 和 dateTimeValue2。
第 2 步 - 定义一个函数 分钟Diff,它将两个日期值作为参数。
步骤 3 - 在函数中,通过减去日期值并将其除以 1000 来计算时差。将结果再次除以 60 即可得到分钟。
第 4 步 - 显示分钟差异作为结果。
示例 2
在此示例中,我们无需使用函数即可计算时间差。
dateTimeValue1 = new Date(2020,12,12);
console.log("The first date time value is defined as: ", dateTimeValue1)
dateTimeValue2 = new Date(2020,12,13);
console.log("The second date time value is defined as: ", dateTimeValue2)
console.log(" The difference in the two date time values in minutes is: ")
var differenceValue =(dateTimeValue2.getTime() - dateTimeValue1.getTime()) / 1000;
differenceValue /= 60;
let result = Math.abs(Math.round(differenceValue))
console.log(result)说明
步骤 1 - 定义两个日期时间值 dateTimeValue1 和 dateTimeValue2。
步骤 2 - 通过减去日期值并将其除以 1000 来计算时差。将结果再次除以 60 即可得到分钟。
第 3 步 - 显示分钟差作为结果。
声明
1、部分文章来源于网络,仅作为参考。 2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!



