JavaScript Date valueOf() 方法
JavaScript Date.valueOf() 方法返回一个数值,表示日期对象与 Epoch 之间的毫秒数。如果提供的 Date 对象无效,此方法将返回非数字 (NaN)。
Epoch 是以秒为单位测量时间的起点,定义为 1970 年 1 月 1 日 00:00:00 UTC。
语法
以下是 JavaScript Date valueOf() 方法的语法 -
valueOf();
此方法不接受任何参数。
返回值
此方法返回日期对象与 UTC 时间 1970 年 1 月 1 日午夜之间的毫秒数。
示例 1
在下面的示例中,我们演示了 JavaScript Date valueOf() 方法的基本用法 -
<html> <body> <script> const currentDate = new Date(); const numericValue = currentDate.valueOf(); document.write(numericValue); </script> </body> </html>
输出
程序返回一个整数,该整数指定日期对象与纪元之间的毫秒数。
示例 2
此处,我们返回特定日期(2023 年 12 月 26 日 12:30:00)自纪元以来的毫秒数 -
<html>
<body>
<script>
const currentDate = new Date('December 26, 2023 12:30:00');
const specificDate = currentDate.valueOf();
document.write(specificDate);
</script>
</body>
</html>
输出
返回"1703574000000"毫秒作为输出。
示例 3
在下面的示例中,日期对象是使用无效日期创建的,即日期和时间值超出了有效范围。
<html>
<body>
<script>
const currentDate = new Date('December 45, 2023 21:78:001');
const specificDate = currentDate.valueOf();
document.write(specificDate);
</script>
</body>
</html>
输出
程序返回"无效日期"。

