JavaScript Date getTime() 方法
在 JavaScript 中,Date.getTime() 方法将返回一个数值,该数值表示日期对象与纪元 (Epoch) 之间的毫秒数。纪元是测量时间的起点(以秒为单位),定义为 1970 年 1 月 1 日 00:00:00 UTC。
当提供的 Date 对象无效时,此方法将返回非数字 (NaN)。返回值始终为非负整数。
此方法的功能与 valueOf() 方法相同。
语法
以下是 JavaScript Date getTime() 方法的语法 -
getTime();
此方法不接受任何参数。
返回值
此方法返回一个数值,表示指定日期和时间与 Unix 纪元之间的毫秒数。
示例 1
在下面的示例中,我们演示了 JavaScript Date getTime() 方法的用法 -
<html> <body> <script> const currentDate = new Date(); const timestamp = currentDate.getTime(); document.write(timestamp); </script> </body> </html>
输出
上述程序返回自纪元以来的毫秒数。
示例 2
在下面的示例中,我们向 date 对象提供了一个具体的日期和时间 (2023-12-26 06:30:00) -
<html>
<body>
<script>
const currentDate = new Date('2023-12-26 06:30:00');
const timestamp = currentDate.getTime();
document.write(timestamp);
</script>
</body>
</html>
输出
返回"1703574000000"毫秒作为输出。
示例 3
在下面的示例中,日期对象是使用无效日期创建的,即日期和时间值超出了有效范围。
<html>
<body>
<script>
const specificDate = new Date('2023-15-56 06:30:00');
const dateString = specificDate.getTime();
document.write(dateString);
</script>
</body>
</html>
输出
程序返回结果"NaN"。

