JavaScript Date toLocaleString() 方法



JavaScript 中的 Date.toLocaleString() 方法用於將 Date 物件轉換為字串,該字串以特定於區域設定的格式表示日期和時間,並基於當前區域設定。

語法

以下是 JavaScript Date toLocaleString() 方法的語法:

toLocaleString(locales, options);

引數

此方法接受兩個引數。下面描述了這兩個引數:

  • locales (可選) − 一個字串或字串陣列,表示 BCP 47 語言標籤,或此類字串的陣列。它指定一個或多個用於日期格式化的區域設定。如果 locales 引數未定義或為空陣列,則使用執行時的預設區域設定。
  • options (可選) − 一個物件,允許您自定義格式。它可以具有諸如 weekday、year、month、day、hour、minute、second 等屬性,具體取決於您是在格式化日期還是時間。

返回值

此方法返回 Date 物件作為字串,使用區域設定。

示例 1

在下面的示例中,我們演示了 JavaScript Date toLocaleString() 方法的基本用法:

<html>
<body>
<script>
   const currentDate = new Date();
   const formattedDate = currentDate.toLocaleString();

   document.write(formattedDate);
</script>
</body>
</html>

輸出

它返回一個 Date 物件作為字串,使用區域設定。

示例 2

在這裡,我們使用 toLocaleString() 方法以及特定的選項來根據英文(美國)區域設定格式化日期,以顯示長星期幾、年份、月份和日期。

<html>
<body>
<script>
   const currentDate = new Date();
   const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
   const formattedDate = currentDate.toLocaleString('en-US', options);

   document.write(formattedDate);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,它根據指定的格式顯示日期。

示例 3

在此示例中,我們自定義時間格式以在 12 小時時鐘中顯示小時、分鐘和秒,併為一位數的值使用前導零。

<html>
<body>
<script>
   const currentDate = new Date();
   const options = { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true };
   const formattedDate = currentDate.toLocaleString('en-US', options);

   document.write(formattedDate);
</script>
</body>
</html>

輸出

正如我們在輸出中看到的,它以 12 小時時鐘格式顯示日期。

廣告