如何在 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 中计算两个日期之间的分钟数?的详细内容,更多请关注双恒网络其它相关文章!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。