- Instant help with your JavaScript coding problems

Get yesterday's date in JavaScript

Question:
How to get yesterday's date in JavaScript?
Answer:
let today = new Date();
let yesterday = new Date();

yesterday.setDate(today.getDate() - 1);

console.log('Today: ' + today);
console.log('Yesterday: ' + yesterday);
Description:

The setDate() method sets the day of the Date object relative to the beginning of the currently set month.


If the dayValue is outside of the range of date values for the month, setDate() will update the Date object accordingly. For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month. If a negative number is provided for dayValue, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month.

Reference:
setDate() manual
Share "How to get yesterday's date in JavaScript?"