Computer >> Máy Tính >  >> Lập trình >> Javascript

Làm cách nào để trừ một tuần kể từ ngày này trong JavaScript?

Bạn cần trừ đi một tuần, tức là 7 ngày kể từ ngày hiện tại. Sau đây là cú pháp -

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

Đầu tiên, hãy lấy ngày hiện tại -

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

Bây giờ, hãy đặt ngày mới bằng phương thức setDate () và trừ đi 7 ngày -

Ví dụ

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);

Để chạy chương trình trên, bạn cần sử dụng lệnh sau -

node fileName.js.

Đây, tên tệp của tôi là demo60.js.

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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)