Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Trừ 1 tuần (7 ngày) từ ngày hiện tại trong JavaScript

Để trừ 1 tuần (tức 7 ngày) từ ngày hiện tại, bạn sử dụng phương thức setDate() kết hợp với getDate().

Cú pháp

var newDate = new Date(currentDate.setDate(currentDate.getDate() - 7));

Ví dụ

var currentDate = new Date();
console.log("Ngày hiện tại: " + currentDate);

var oneWeekAgo = new Date(currentDate.setDate(currentDate.getDate() - 7));
console.log("Ngày trước 1 tuần: " + oneWeekAgo);

Cách chạy

Lưu file (ví dụ: demo.js) và chạy lệnh:

node demo.js

Kết quả mẫu

Ngày hiện tại: Tue Jul 14 2020 19:12:43 GMT+0700 (Indochina Time)
Ngày trước 1 tuần: Tue Jul 07 2020 19:12:43 GMT+0700 (Indochina Time)

Lưu ý: Phương thức setDate() tự động xử lý việc chuyển tháng/năm khi ngày bị âm.