如何在 JavaScript 中計算兩個日期之間的分鐘數?
在本文中,您將瞭解如何在 JavaScript 中計算兩個日期之間的分鐘數。
Date 物件用於處理日期和時間。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 − 定義一個函式 `minutesDiff`,它接受兩個日期值作為引數。
步驟 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 − 顯示分鐘差作為結果。
廣告