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 对象。