在 JavaScript 中,Date.getTime() 方法将返回一个数值,该值表示 date 对象和 Epoch 之间的毫秒数。纪元是测量时间(以秒为单位)的起点,定义为 1970 年 1 月 1 日 00:00:00 UTC。
当提供的 Date 对象无效时,此方法将返回 Not a Number (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>
输出
上面的程序返回自 epoch 以来的毫秒数。
示例 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” 作为结果。