JavaScript Date.setMilliseconds() 方法用于设置日期对象的“毫秒”。毫秒值的范围是 0 到 999。在设置毫秒组件后,它返回日期对象的时间与 1970 年 1 月 1 日午夜之间的毫秒数。
如果提供的日期对象为“无效”,则此方法将返回 Not a Number (NaN) 作为结果。此方法修改日期对象的毫秒部分,而不更改其他日期组件。
语法
以下是 JavaScript Date.setMilliseconds() 方法的语法 -
setMilliseconds(millisecondsValue);
参数
此方法只接受一个参数。下面描述相同 -
- millisecondsValue - 表示毫秒(0 到 999)的整数。
- 如果提供 -1,则会导致前一秒的最后一毫秒。
- 如果提供 1000,则会导致下一秒的第一毫秒。
返回值
此方法不返回新的 date 对象。相反,它通过将 Date 对象的毫秒组件设置为指定值来修改现有对象。
示例 1
在以下示例中,我们使用 JavaScript Date.setMilliseconds() 方法将当前 Date 的“毫秒”设置为 500 -
<html>
<body>
<script>
const myDate = new Date();
myDate.setMilliseconds(500);
document.write(myDate.getMilliseconds());
</script>
</body>
</html>
输出
如果我们执行上述程序,毫秒数将设置为 500。
示例 2
在这里,我们将当前日期增加 300000 毫秒 -
<html>
<body>
<script>
const currentDate = new Date();
const millisecondsToAdd = 300000; // Add 5 minutes (300000 milliseconds)
currentDate.setMilliseconds(currentDate.getMilliseconds() + millisecondsToAdd);
document.write(currentDate);
</script>
</body>
</html>
输出
上述程序将为当前日期增加 5 分钟。
示例 3
如果我们为 millisecondsValue 提供 “-1”,则此方法将给出前一秒的最后一毫秒 -
<html>
<body>
<script>
const myDate = new Date();
myDate.setMilliseconds(-1);
document.write(myDate.getMilliseconds());
</script>
</body>
</html>
输出
此方法返回 “999” 作为前一秒的最后一毫秒。
示例 4
如果我们为 millisecondsValue 提供 “1000”,则此方法将给出下一秒的第一毫秒 -
<html>
<body>
<script>
const myDate = new Date();
myDate.setMilliseconds(1000);
document.write(myDate.getMilliseconds());
</script>
</body>
</html>
输出
此方法返回 “0” 作为下一秒的第一毫秒。