在本文中,您将了解如何在 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。
-
步骤 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 中计算两个日期之间的分钟数?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。