JavaScript Date toUTCString() 方法
JavaScript Date.toUTCString() 方法用于根据协调世界时 (UTC) 将日期对象转换为字符串。在 JavaScript 中创建 Date 对象时,它代表一个特定的时间点,但没有关联的时区。但此方法允许您将此日期对象转换为字符串表示形式,以指示其位于 UTC 时区。
UTC 代表协调世界时。它是世界各国规范时钟和时间的主要时间标准。
JavaScript 中的 "Date.toGMTString()" 是此方法的别名。
语法
以下是 JavaScript Date toUTCString() 方法的基本语法 -
toUTCString();
此方法不接受任何参数。
返回值
此方法返回一个字符串,该字符串表示给定的 UTC 时区日期。
示例 1
以下是 JavaScript Date toUTCString() 方法的基本演示 -
<html> <body> <script> const date = new Date(); const UTCString = date.toUTCString(); document.write(UTCString); </script> </body> </html>
输出
它根据 UTC 返回 Date 对象的字符串。
示例 2
在下面的示例中,我们将创建一个特定日期和时间的 Date 对象,然后将其转换为 UTC 格式的字符串。
<html>
<body>
<script>
const specificDate = new Date('2023-01-01T12:00:00');
const UTCString = specificDate.toUTCString();
document.write(UTCString);
</script>
</body>
</html>
输出
上述程序返回结果"Sun, 01 Jan 2023 06:30:00 GMT"。
示例 3
如果 Date 对象无效,此方法将返回结果"Invalid date" -
<html>
<body>
<script>
const specificDate = new Date('2023764-01-01T12:00:00');
const UTCString = specificDate.toUTCString();
document.write(UTCString);
</script>
</body>
</html>
输出
正如我们在输出中看到的,它没有返回日期字符串格式的 Date 对象。

