簡體   English   中英

將 UTC 時間戳轉換為 ISO 格式的其他時區

[英]Convert UTC timestamp to other timezone in ISO format

我正在嘗試將 UTC 時間戳轉換為德國時間的 ISO 格式時間戳。

輸入: 2022-04-30T17:30:00.000000Z

預計 Output: 2022-04-30T19:30:00

這是我目前的工作解決方案,但感覺非常......hacky......至少可以這么說。 一方面,恐怕許多瀏覽器可能無法將日期正確轉換為德國時區。

 var inputDateString = "2022-04-30T17:30:00.000000Z"; // Convert to German timezone and formatted as iso date var output = toIsoString(convertTZ(inputDateString, "Europe/Berlin")).split("+")[0]; console.log("inputDateString:", inputDateString) console.log("output:", output) // Ref.: https://stackoverflow.com/a/54127122 function convertTZ(date, tzString) { return new Date((typeof date === "string"? new Date(date): date).toLocaleString("en-US", { timeZone: tzString })); } // Ref.: https://stackoverflow.com/a/17415677 function toIsoString(date) { var tzo = -date.getTimezoneOffset(), dif = tzo >= 0? "+": "-", pad = function (num) { return (num < 10? "0": "") + num; }; return date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()) + "T" + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds()) + dif + pad(Math.floor(Math.abs(tzo) / 60)) + ":" + pad(Math.abs(tzo) % 60); }

您知道與大多數瀏覽器兼容的更好/改進的解決此問題的方法嗎? 我覺得 JavaScript 必須為這項任務提供更好的解決方案,而不必依賴外部庫......

編輯:作為toIsoString function 的替代方案,我還發現了這個: .toLocaleString("sv-SE")但我認為這對瀏覽器的支持更差。

如果您不需要保證結果時間戳的格式,您可以使用toLocaleDateString加上帶有合適語言標簽的toLocaleTimeString ,例如

 function getISOLocal(loc, date = new Date()) { return `${date.toLocaleDateString('en-CA', {timeZone: loc})}` + `T${date.toLocaleTimeString('en', {timeZone: loc, hour12:false})}`; } console.log('Current local time in:'); ['Pacific/Midway', 'America/New_York', 'Europe/Berlin', 'Pacific/Kiritimati'].forEach( loc => console.log(`${loc}: ${getISOLocal(loc)}`) );

但請注意, toLocale*方法的格式取決於實現,並且可能因實現而異,特別是對於不太常見的語言以及語言、選項和主機默認語言的組合。

更好的選擇是將Intl.DateTimeFormatformatToParts一起使用,例如

 function getISOLocal(loc, date = new Date()) { let {year, month, day, hour, minute, second} = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, timeZone: loc }).formatToParts(date).reduce((acc, part) => { acc[part.type] = part.value; return acc; }, Object.create(null)); return `${year}-${month}-${day}T${hour}:${minute}:${second}` } console.log('Current local time in:'); ['Pacific/Midway', 'America/New_York', 'Europe/Berlin', 'Pacific/Kiritimati'].forEach( loc => console.log(`${loc}: ${getISOLocal(loc)}`) );

IE 不支持timeZone選項,但也許這無關緊要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM