首页  >  文章  >  web前端  >  如何在 JavaScript 中计算两个日期之间的分钟数?

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

PHPz
PHPz转载
2023-09-05 14:33:02656浏览

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

在本文中,您将了解如何在 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 步 - 显示分钟差作为结果。

以上是如何在 JavaScript 中计算两个日期之间的分钟数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除