如何在 JavaScript 中计算两个日期之间的分钟数?


在本文中,您将了解如何在 JavaScript 中计算两个日期之间的分钟数。

Date 对象用于处理日期和时间。Date 对象使用 `new Date()` 创建。JavaScript 将使用浏览器的时区并将日期显示为完整的文本字符串。

示例 1

在这个示例中,我们使用一个函数来查找时间差。

Open Compiler
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 − 定义一个函数 `minutesDiff`,它接受两个日期值作为参数。

  • 步骤 3 − 在函数中,通过减去日期值并将其除以 1000 来计算时间差。再次将结果除以 60 以获得分钟数。

  • 步骤 4 − 显示分钟差作为结果。

Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.

示例 2

在这个示例中,我们无需函数即可计算时间差。

Open Compiler
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 − 显示分钟差作为结果。

更新于:2023年2月16日

11K+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告