如何在 JavaScript 中將日期轉換為其他時區?
JavaScript 具有一個新的 Date() 建構函式,用於建立日期物件以獲取當前日期和時間。此日期物件使用 UTC 時區或客戶端瀏覽器的時區,即如果您在印度並使用 new Date() 建構函式獲取日期和時間,您將獲得本地時間。但有時,我們可能需要獲取另一個國家的時區,而我們無法直接做到這一點。這些可以透過使用 toLocaleString() 方法或 format() 方法來完成。在本文結束時,您將能夠在 JavaScript 中獲取任何其他時區的日期。
我們在本文中將使用的兩種將日期轉換為另一個時區的方法如下:
使用 toLocaleString() 方法
使用 format() 方法
使用 toLocaleString() 方法
toLocaleString() 方法可以使用日期物件呼叫。此方法能夠根據傳遞的引數將資料從一個時區轉換為另一個時區。它接受兩個引數,第一個是“locale”,即應使用其格式約定語言,對於英語它是“en-US”,第二個是“options”,對於我們來說是 {timeZone:"countryName"},其中 countryName 是我們想要更改時區的國家/地區的名稱。
以下是使用 toLocaleString() 方法在 JavaScript 中將日期轉換為其他時區的逐步過程。
使用 Date 建構函式建立日期物件
將日期物件與 toLocaleString() 方法一起使用,並將第一個引數作為 'en-US' 用於英語日期和時間格式,並將第二個引數 {timeZone: "America/New_York"} 用於獲取紐約的時區
將此方法返回的值儲存到一個變數中,該變數是我們所需的時區。
示例
在此示例中,我們使用 toLocaleString() 方法在 JavaScript 中將日期轉換為其他時區。
<!DOCTYPE html> <html lang="en"> <head> <title>Converting date to another timezone in JavaScript</title> </head> <body> <h3>Convert date to America/New_York Time Zone using toLocaleString() Method</h3> <p id="input">Local Time: </p> <p id="output">America/New_York Time Zone: </p> <script> // date objec let date = new Date(); document.getElementById("input").innerText += date ; // convert date to another timezone let output = date.toLocaleString("en-US", { timeZone: "America/New_York" }); // display the result document.getElementById("output").innerText += output; </script> </body> </html>
使用 Format() 方法
我們可以將 format() 方法與“Intl.DateTimeFormat”物件一起使用,並將作為引數傳遞給 format() 方法的日期物件用於將時區轉換為在建立“Intl.DateTimeFormat”物件時傳遞的時區。聽起來很複雜,但如果您檢視下面的示例,它非常簡單。
以下是使用 format() 方法在 JavaScript 中將日期轉換為其他時區的逐步過程。
使用 Date 建構函式建立日期物件。
建立“Intl.DateTimeFormat”物件,同時將第一個引數作為 'en-US' 用於英語日期和時間格式,並將第二個引數 {timeZone: "America/New_York"} 用於獲取紐約的時區。
使用此物件使用 format() 方法並將日期物件作為引數傳遞,並將其儲存在一個變數中,該變數是我們所需的時區。
示例
在此示例中,我們使用 format() 方法在 JavaScript 中將日期轉換為其他時區。
<!DOCTYPE html> <html lang="en"> <head> <title>Convert date to America/New_York timezone in JavaScript</title> </head> <body> <h3>Convert date to America/New_York timezone using format() Method</h3> <p id="input">Local Time: </p> <p id="output">America/New_York Time Zone: </p> <script> // date objec let date = new Date(); document.getElementById("input").innerText += date ; // create a new date object let newObj = Intl.DateTimeFormat('en-US', { timeZone: "America/New_York" }) // convert date to another timezone let newDate = newObj.format(date); // display the result document.getElementById("output").innerHTML += newDate; </script> </body> </html>
總結
讓我們總結一下在本教程中學到的內容。我們看到我們有兩種方法可以將日期轉換為其他時區,第一種是使用日期物件的 toLocaleString() 方法,第二種是使用“Intl.DateTimeFormat”物件的 format() 方法。兩種方法都有不同的用例,您可以根據需要選擇。我們推薦使用 toLocaleString() 方法,它易於使用,並且所需的程式碼行數少於使用“Intl.DateTimeFormat”物件的 format() 方法。