Get Yesterday’s Date
const today = new Date(); console.log('Today:', today); const current_date = today.getDate(); var yesterday = today; yesterday.setDate(current_date-1); console.log('Yesterday:', yesterday);
Today: 2022-08-31T03:39:46.617Z Yesterday: 2022-08-30T03:39:46.617Z
You can use the Date() constructor to create an instance of Date. With no arguments, it returns an object representing the current date and time.
In the example above, we use the today object to hold the representation of the time of instantiation. This can be verified by the output printed out by console.log().
The Date.getDate() method can be used to get the day (of the month) of any Date object, including today. In our example, the current_date variable holds this value (which is 31).
To get yesterday’s date, we need to subtract the day value by one and set it to a Date object. That is what the Date.setDate() method is designed for. It can change the day of Date objects.
We create a new Date object to hold the time and date of yesterday. Its day value should now be set back by one with the setDate() method with this statement:
The yesterday object now contains the time of instantiation, but one day ago.
Output Yesterday’s Date As YYYY-MM-DD
If you want to print both the date and time of yesterday, use the toString() method. Its returned string represents the Date object in the local time.
Tue Aug 30 2022 10:39:46 GMT+0200 (CEST)
Since toString() uses your local timezone to interpret Date objects, the returned value varies across locations.
When you only want to get the date part of a Date object, use toDateString():
Tue Aug 30 2022
If you want to change the format of these strings using the conventions of a specific language, use toLocaleString() and toLocaleDateString(). For instance, this is how you can print the date (and time) portions of our yesterday object with the British English format:
30/08/2022, 10:39:46 30/08/2022
There are many languages and varieties that use the YYYY-MM-DD format around the world, such as Canadian English. You can set the locale parameter of toLocaleDateString() to these language codes to print yesterday’s date in YYYY-MM-DD:
Additionally, you can also make use of the toISOString() method, which returns a representation in the ISO 8601 format. Because only the first ten characters of this string are needed, we use the slice() method to get our output:
const time = yesterday.toISOString().slice(0, 10); console.log('Yesterday (YYYY-MM-DD):', time);
Yesterday (YYYY-MM-DD): 2022-08-30
To learn more about toISOString(), read this guide.