如何在 JavaScript 日期物件中新增 10 秒?


在本教程中,我們將學習如何在 JavaScript 日期物件中新增 10 秒。我們將討論以下兩種方法。

  • 使用 setSeconds() 方法

  • 使用 getTime() 方法

使用 setSeconds() 方法

JavaScript 日期物件的 setSeconds() 方法根據本地時間設定指定日期的秒數。此方法接受兩個引數,第一個引數是 0 到 59 之間的秒數,第二個引數是 0 到 999 之間的毫秒數。

如果您未指定第二個引數,則使用 getMilliseconds() 方法返回的值。如果您指定的引數超出預期範圍,setSeconds() 方法將嘗試相應地更新 Date 物件中的日期資訊。

例如,如果您將秒值設定為 100,則 Date 物件中儲存的分鐘將遞增 1,秒將使用 40。

語法

Date.setSeconds(seconds, ms)

引數

  • seconds − 這是一個 0 到 59 之間的整數,表示秒數。如果您指定了 seconds 引數,則也必須指定 minutes

  • ms − 這是一個 0 到 999 之間的數字,表示毫秒數。如果您指定了 ms 引數,則也必須指定 minutesseconds

方法

要使用 setSeconds() 方法在 Date 物件中新增 10 秒,我們首先獲取當前時間的秒數的值,然後向其中新增 10,並將新增後的值傳遞給 setSeconds() 方法。

示例

在這個例子中,我們使用 setSeconds() 方法向當前時間新增 10 秒。

<html> <head> <title>Example- adding 10 seconds to a JavaScript date object</title> </head> <body> <h3> Add 10 seconds to the JavaScript Date object using setSeconds( ) method </h3> <p> Click on the button to add 10 seconds to the current date/time.</p> <button onclick="add()">Click Me</button> <p id="currentTime">Current Time : </p> <p id="updatedTime">Updated Time: </p> </body> <script> // Code the show current time let ct = document.getElementById("currentTime") setInterval(() => { let currentTime = new Date().getTime(); ct.innerText = "Current Time : " + new Date(currentTime).toLocaleTimeString() }, 1000) // Code to add 10 seconds to current Time let ut = document.getElementById("updatedTime") function add() { setInterval(() => { let dt = new Date(); dt.setSeconds(dt.getSeconds() + 10); ut.innerText = "Updated Time : " + dt.toLocaleTimeString(); }, 1000) } </script> </html>

使用 getTime() 方法

JavaScript 日期物件的 getTime() 方法根據世界標準時間返回與指定日期時間對應的數值。getTime() 方法返回的值是從 1970 年 1 月 1 日 00:00:00 算起的毫秒數。

語法

Date.getTime()

方法

要在 Date 物件中新增 10 秒,首先,我們使用 Date.getTime() 方法獲取當前時間,然後向其中新增 10000 毫秒,並將新增後的值傳遞給 Date 物件。

示例

在這個例子中,我們使用 getTime() 方法向當前時間新增 10 秒。

<html> <head> <title>Example – adding 10 seconds to Date object</title> </head> <body> <h3> Add 10 seconds to the JavaScript Date object </h3> <p> Click on the button to add 10 seconds to the current date/time.</p> <button onclick="add()">Click Me</button> <p id="currentTime">Current Time : </p> <p id="updatedTime">Updated Time: </p> </body> <script> // Code the show current time let ct = document.getElementById("currentTime") setInterval(() => { let currentTime = new Date().getTime(); ct.innerText = "Current Time : " + new Date(currentTime).toLocaleTimeString() }, 1000) // Code to add 10 seconds to current Time let ut = document.getElementById("updatedTime") function add() { setInterval(() => { let currentTime = new Date().getTime(); let updatedTIme = new Date(currentTime + 10000); ut.innerText = "Updated Time : " + updatedTIme.toLocaleTimeString() }, 1000) } </script> </html>

總而言之,我們討論了兩種向 JavaScript 日期物件新增 10 秒的方法。第一種方法是使用 setSeconds() 方法,第二種方法是使用 getTime() 方法。

更新於:2022年8月22日

4K+ 瀏覽量

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告