如何在 JavaScript 中從該日期中減去一週?


你需要從當前日期減去一週,即 7 天。以下是語法 -

var anyVariableName=new Date(yourCurrentDate.setDate(yourCurrentDate.getDate() - 7)

首先,獲取當前日期 -

var currentDate = new Date();
console.log("The current Date="+currentDate);

現在,使用 setDate() 方法設定新日期並減去 7 天 -

示例

var currentDate = new Date();
console.log("The current Date="+currentDate);
var before7Daysdate=new Date(currentDate.setDate(currentDate.getDate() - 7));
console.log("The One week ago date="+before7Daysdate);

要執行上面的程式,你需要使用以下命令 -

node fileName.js.

這裡,我的檔名是 demo60.js。

輸出

這將產生以下輸出 -

PS C:\Users\Amit\JavaScript-code> node demo60.js
The current Date=Tue Jul 14 2020 19:12:43 GMT+0530 (India Standard Time)
The One week ago date=Tue Jul 07 2020 19:12:43 GMT+0530 (India Standard Time)

更新於:2020-09-03

2K+ 觀看

開啟您 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.