JavaScript Date.valueOf() 方法返回一个数值,该值表示 date 对象和 Epoch 之间的毫秒数。如果提供的 Date 对象无效,则此方法将返回 Not a Number (NaN) 作为结果。
纪元是测量时间(以秒为单位)的起点,定义为 1970 年 1 月 1 日 00:00:00 UTC。
语法
以下是 JavaScript Date valueOf() 方法的语法 -
valueOf();
此方法不接受任何参数。
返回值
此方法返回日期对象与 1970 年 1 月 1 日午夜 UTC 之间的毫秒数。
示例 1
在下面的示例中,我们将演示 JavaScript Date valueOf() 方法的基本用法 -
<html>
<body>
<script>
const currentDate = new Date();
const numericValue = currentDate.valueOf();
document.write(numericValue);
</script>
</body>
</html>
输出
该程序返回一个整数,该整数指定 date 对象和 epoch 之间的毫秒数。
示例 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>
输出
程序将返回 “invalid date” 作为结果。