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

Làm cách nào để lấy ngày hôm qua trong JavaScript?

Để lấy ngày hôm qua, trước hết hãy lấy ngày hiện tại và trừ 1 cho hiện tại và sử dụng hàm setDate (). Cú pháp như sau -

yourCurrentDateVariableName.setDate(yourCurrentDateVariableName.getDate() - 1);

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

var currentDate = new Date();

Bây giờ, hãy xem ngày hôm qua với mã sau -

Ví dụ

var currentDate = new Date();
console.log("The current date="+currentDate);
var yesterdayDate = currentDate.setDate(currentDate.getDate()- 1);
console.log("The yesterday date ="+new Date(yesterdayDate));

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

node fileName.js.

Đầu ra

Ở đây, tên tệp của tôi là demo137.js. Điều này sẽ tạo ra kết quả sau -

PS C:\Users\Amit\JavaScript-code> node demo137.js
The current date=Fri Jul 31 2020 18:57:17 GMT+0530 (India Standard Time)
The yesterday date =Thu Jul 30 2020 18:57:17 GMT+0530 (India Standard Time)