JavaScript Date setMilliseconds() 方法



JavaScript 的 Date.setMilliseconds() 方法用於設定日期物件的“毫秒”。毫秒值可以是 0 到 999。它返回日期物件的時間與 1970 年 1 月 1 日午夜之間的毫秒數,在設定了毫秒分量之後。

如果提供的日期物件“無效”,則此方法返回非數字 (NaN) 作為結果。此方法修改日期物件的毫秒分量,而不更改其他日期分量。

語法

以下是 JavaScript Date setMilliseconds() 方法的語法:

setMilliseconds(millisecondsValue);

引數

此方法只接受一個引數。下面描述了該引數:

  • millisecondsValue − 表示毫秒的整數(0 到 999)。
    • 如果提供 -1,則結果將是前一秒的最後毫秒。
    • 如果提供 1000,則結果將是下一秒的第一毫秒。

返回值

此方法不會返回新的日期物件。相反,它透過將其毫秒分量設定為指定值來修改現有的 Date 物件。

示例 1

在下面的示例中,我們使用 JavaScript Date setMilliseconds() 方法將當前日期的“毫秒”設定為 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”作為下一秒的第一毫秒。

廣告