JavaScript Date valueOf() 方法



JavaScript 的 Date.valueOf() 方法返回一个数值,表示日期对象与纪元之间以毫秒为单位的差值。如果提供的 Date 对象无效,则此方法返回非数字 (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>

输出

程序返回一个整数,该整数指定日期对象与纪元之间的毫秒数。

示例 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>

输出

程序返回“无效日期”作为结果。

广告
© . All rights reserved.