這種用于確定本月最后一天的 javascript 方法不適用于我在烏克蘭,但它適用于我在美國的同事。我得到 2022-10-30,我的同事得到 2022-10-31。問題是什么?
var now = new Date();
const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() 1, 0).toISOString().split('T')[0];
console.log(lastDayOfMonth)
我創建了一個 codepen,我們得到了不同的結果:
Сodepen 檢查
uj5u.com熱心網友回復:
這是因為時區。new Date在本地時間作業,但toISOString格式化日期/時間的 UTC 版本。由于您領先于 UTC,因此您在午夜的本地日期/時間是 UTC 的前一天。但是在美國,他們落后于 UTC(而且他們也有相反的問題),所以它對他們有用。
而是從午夜 UTC 開始,通過以下UTC方法:
const now = new Date();
const lastDayOfMonth = new Date(Date.UTC(now.getFullYear(), now.getMonth() 1, 0))
.toISOString()
.split("T")[0];
console.log(lastDayOfMonth);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/522198.html
標籤:javascript日期
