Occasionally you may want to calculate yesterday’s date using JavaScript. Here are three methods you can use to do so.
Method 1: Using Today’s DateĀ
Using this method, we define today’s date, then subtract one day from it:
var today = new Date(); today.setDate(today.getDate()-1); console.log(today.toDateString()); // Wed Sep 30 2020
Method 2: Using Milliseconds
Using this method, we simply subtract 86,400,000 milliseconds (the number of seconds in one day) from today’s date:
var yesterday = new Date(Date.now() - 864e5); console.log(yesterday.toDateString()); // Wed Sep 30 2020
Method 3: Using Moment.js
Using this method, we can simply use the subtract() function from the Moment.js JavaScript library:
moment().subtract(1, 'days'); // Wed Sep 30 2020