Để lấy ngày hôm qua, trước hết lấy ngày hiện tại và trừ 1 từ ngày hiện tại và sử dụng hàm setDate(). Cú pháp như sau:
yourCurrentDateVariableName.setDate(yourCurrentDateVariableName.getDate() - 1);
Trước tiên, lấy ngày hiện tại:
var currentDate = new Date();
Bây giờ, lấy ngày hôm qua với mã sau:
Ví dụ
var currentDate = new Date();
console.log("Ngày hiện tại=" + currentDate);
var yesterdayDate = currentDate.setDate(currentDate.getDate() - 1);
console.log("Ngày hôm qua =" + new Date(yesterdayDate));
Để chạy chương trình trên, bạn cần sử dụng lệnh sau:
node fileName.js
Kết quả
Tên tệp của tôi là demo137.js. Chương trình sẽ cho ra kết quả sau:
PS C:\Users\Amit\JavaScript-code> node demo137.js Ngày hiện tại=Fri Jul 31 2020 18:57:17 GMT+0530 (India Standard Time) Ngày hôm qua =Thu Jul 30 2020 18:57:17 GMT+0530 (India Standard Time)