JavaScript Date toJSON() 方法



JavaScript 的 Date.toJSON() 方法用於將 Date 物件轉換為表示給定日期的字串,該字串採用日期時間 JSON 字串格式,並根據世界標準時間顯示。如果 Date 物件為無效日期,則此方法返回“null”。此外,此方法不接受任何引數。

語法

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

toJSON();

此方法不接受任何引數。

返回值

一個字串,表示給定日期的日期時間字串格式,根據世界標準時間。

示例 1

在下面的示例中,我們使用 JavaScript toJSON() 方法將當前日期和時間轉換為 JSON 格式的字串。

<html>
<body>
<script>
   const currentDate = new Date();
   const jsonDate = currentDate.toJSON();

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

輸出

正如我們看到的輸出,此方法返回一個格式化的 JSON 字串。

示例 2

在這裡,我們使用特定的日期和時間“2023-12-31T08:15:30”建立一個日期物件:

<html>
<body>
<script>
   const customDate = new Date('2023-12-31T08:15:30');
   const jsonCustomDate = customDate.toJSON();

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

輸出

程式將特定的日期和時間轉換為格式化的 JSON 字串。

示例 3

在這裡,我們將日期值提供為“50”,該值超出範圍。

<html>
<body>
<script>
   const currentDate = new Date('2023-12-50T05:06:01.516Z');
   const jsonDate = currentDate.toJSON();

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

輸出

如果我們執行程式,則將返回“null”作為輸出。

示例 4

在下面的示例中,我們將日期物件增加 10 天,並將修改後的日期轉換為 JSON 格式的字串。

<html>
<body>
<script>
   const futureDate = new Date();
   futureDate.setDate(futureDate.getDate() + 10);

   const jsonFutureDate = futureDate.toJSON();

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

輸出

結果將是一個字串,表示未來 10 天的日期和時間。

廣告