JavaScript Date toString() 方法



JavaScript 的 Date.toString() 方法用於將 Date 物件轉換為字串。返回值將是一個字串,表示根據本地時區的時間、日期和時區。

對於諸如數字、布林值和字串之類的原始值,toString() 返回轉換為字串的原始值。如果 Date 物件“無效”,則此方法返回 “invalid date” 作為結果。對於 null 和 undefined,toString() 分別返回“null”和“undefined”的字串表示形式。

語法

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

toString();

此方法不接受任何引數。

返回值

此方法返回表示為字串的日期和時間。

示例 1

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

<html>
<body>
<script>
   const currentDate = new Date();
   const dateString = currentDate.toString();

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

輸出

以上程式將日期物件作為字串返回。

示例 2

在下面的示例中,我們為日期物件提供了一個特定的日期和時間 (2023-12-26 06:30:00):-

<html>
<body>
<script>
   const specificDate = new Date('2023-12-26 06:30:00');
   const dateString = specificDate.toString();

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

輸出

它將日期轉換為字串並返回。

示例 3

這裡,日期物件是用無效日期建立的,即超出有效範圍的日期和時間值。

<html>
<body>
<script>
   const specificDate = new Date('2023-15-56 06:30:00');
   const dateString = specificDate.toString();

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

輸出

程式返回“invalid date”作為結果。

廣告