如何在 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() 方法將 10 秒新增到 Date 物件中,首先我們獲取當前時間的秒數的值,然後向其中新增 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()

方法

要將 10 秒新增到 Date 物件,首先,我們使用 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>

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

更新於: 2022 年 8 月 22 日

4K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.