如何在 JavaScript 中為日期新增天數?


在本教程中,我們將學習如何向 JavaScript Date 物件新增一定的天數。我們將討論以下兩種方法。

  • 使用 setDate() 方法

  • 使用 getTime() 方法

使用 setDate() 方法

JavaScript 日期 **setDate()** 方法根據本地時間設定指定日期的月份中的某一天。

語法

其語法如下:

Date.setDate( dayValue )

這裡 **dayValue** 是一個介於 1 到 31 之間的整數,表示月份中的某一天。

方法

要向當前日期新增一定的天數,首先我們使用 getDate() 方法獲取當前日期,然後將要新增的天數加到當前日期,並將新增後的值傳遞給 setDate() 方法。

示例

在此示例中,我們向當前日期新增 2 天。

<!DOCTYPE html> <html> <head> <title>Example- add number of days to the Date object</title> </head> <body> <h2> Add Number of days to the JavaScript Date object using setDate( ) method </h2> <p> Click on the button to add 2 days to the current date/time.</p> <button onclick="add()">Click Me</button> <p id="currentTime">Current Date : </p> <p id="updatedTime">Updated Date: </p> </body> <script> // Code the show current date let ct = document.getElementById("currentTime") setInterval(() => { let currentDate = Date.now(); ct.innerText = "Current Date : " + new Date(currentDate).toLocaleDateString() }, 1000) // Code to add 2 days to current Time let ut = document.getElementById("updatedTime") function add() { setInterval(() => { let dt = new Date(); dt.setDate(dt.getDate() + 2); ut.innerText = "Updated Date : " + dt.toLocaleDateString(); }, 1000) } </script> </html>

**注意** - 日期格式為 MM/DD/YYYY

使用 getTime() 方法

JavaScript 日期 **getTime()** 方法返回對應於指定日期根據世界標準時間的時間的數字值。getTime() 方法返回的值是從 1970 年 1 月 1 日 00:00:00 開始的毫秒數。

語法

Date.getTime()

方法

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

示例

在此示例中,我們使用 getTime() 方法向當前時間新增 2 天。

<html> <body> <h2> Add Number of days to the JavaScript Date object using getTime( ) method </h2> <p> Click on the button to add 2 days to the current date/time.</p> <button onclick="add()">Click Me</button> <p id="currentTime">Current Date : </p> <p id="updatedTime">Updated Date: </p> </body> <script> // Code the show current date let ct = document.getElementById("currentTime") setInterval(() => { let currentDate = Date.now(); ct.innerText = "Current Date : " + new Date(currentDate).toLocaleDateString() }, 1000) // Code to add 2 days to current Time let ut = document.getElementById("updatedTime") function add() { setInterval(() => { let currentTime = new Date().getTime(); let updatedTIme = new Date(currentTime + 2 * 24 * 60 * 60 * 1000); ut.innerText = "Updated Date : " + updatedTIme.toLocaleDateString() }, 1000) } </script> </html>

**注意** - 日期格式為 MM/DD/YYYY

更新於: 2022 年 8 月 22 日

18K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.