How to get yesterday’s date in JavaScript?


To get the yesterday date, first of all get the current date and subtract 1 from the current and use the function setDate(). The syntax is as follows −

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

At first, get the current date −

var currentDate = new Date();

Now, get yesterday’s date with the following code −

Example

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

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo137.js. This will produce the following output −

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)

Updated on: 11-Sep-2020

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements