Date.setTime()方法用于将 Date 对象的时间设置为指定时间,该时间由自 1970 年 1 月 1 日 00:00:00 UTC(也称为 Unix 纪元)以来经过的毫秒数表示。此方法将 Date 对象的时间更改为提供的时间,而不更改其年、月和日组件。
语法
以下是 JavaScript Date.setTime() 方法的语法 -
setTime(timeValue);
一个整数值,表示自纪元(1970 年 1 月 1 日,00:00:00 UTC)以来的时间(以毫秒为单位)。
返回值
此方法不返回值。它会就地修改原始 Date 对象,并将其时间设置为指定值。
示例 1
在下面的示例中,我们将 1577880000000 毫秒(等于 50 年)传递给 JavaScript Date setTime() 方法 -
<html>
<body>
<script>
const date = new Date();
date.setTime(1577880000000); //incrementing 50 years since epoch
document.write(date);
</script>
</body>
</html>
输出
正如我们所看到的,自 epoch 以来已添加 provided 毫秒数。
示例 2
在这里,我们减去 1970 年 1 月 1 日的 1577880000000 毫秒(等于 50 年)−
<html>
<body>
<script>
const date = new Date();
date.setTime(-1577880000000); //decrementing 50 years since epoch
document.write(date);
</script>
</body>
</html>
输出
正如我们所看到的,50 年是从纪元中减去的。