我的后端時間精度有問題。這是代碼示例:
const inputDateString = `2022-05-30 13:45:15` // assume it as UTC without specifying the timezone
// we use loadbalancing and auto-scale so our backend engine might be everywhere,
// so we dont take local time into account, we always treat date as UTC
let systemGetDate = new Date(inputDateString)
console.log(systemGetDate.valueOf()) // => 1653893115000, it should be 1653918315000
// 1653893115000 is GMT: Monday, 30 May 2022 06:45:15, but 2022-05-30 13:45:15 in my local time!
const inputDateStringWithTimezone = `2022-05-30 13:45:15 00`
systemGetDate = new Date(inputDateStringWithTimezone)
console.log(systemGetDate.valueOf()) // => 1653918315000, its right now. but only when timezone explicitly specified
我們可以讓 new Date(string) 始終將輸入視為 UTC,而不將其轉換為本地時間嗎?我很好,Date物件是本地時間,但至少是getTime或valueOf在UTC中。
目前我的解決方法是使用moment.js庫,它可以產生我想要的輸出。
但我知道過分依賴其他庫會很糟糕,它可能會在以后損壞或棄用。(https://momentjs.com/docs/#/-project-status,官方自己說明會停產)
有什么更好的解決方法來解決這個問題?或者我應該從頭開始,并明確指定系統周圍的時區?
uj5u.com熱心網友回復:
const inputDateString = `2022-05-30 13:45:15` // assume it as UTC without specifying the timezone
沒有時區或偏移量的時間戳被視為本地,而不是 UTC。ECMA-262 不支持該特定時間戳的格式,因此決議依賴于實作(請參閱為什么 Date.parse 給出不正確的結果?)并且可能導致無效的日期或意外值。
我們可以讓 new Date(string) 始終將輸入視為 UTC,而不將其轉換為本地時間嗎?
是的,通過將其重新格式化為內置決議器應視為 UTC 的受支持格式,例如:
'2022-05-30T13:45:15Z'
或者,您可以自己決議它并將值傳遞給Date.UTC,以便將它們視為 UTC,例如
let date = `2022-05-30 13:45:15`;
// Reformat and use the built–in parser
let reformattedDate = date.replace(' ','T') 'Z';
console.log(new Date(reformattedDate).toISOString());
// Using Date.UTC
let [Y, M, D, H, m, s] = date.split(/\D/);
let d = new Date(Date.UTC(Y, M-1, D, H, m, s));
console.log(d.toISOString());
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/487171.html
標籤:javascript 日期 约会时间 时间 时代
下一篇:從Java中的當前時間減去小時數
