Date object and subtracting 1 from its
getDate() method. Here is an example code snippet:
// Create a new Date object for the current date const currentDate = new Date(); // Get the year, month, and day of the current date const currentYear = currentDate.getFullYear(); const currentMonth = currentDate.getMonth(); const currentDay = currentDate.getDate(); // Create a new Date object for yesterday's date const yesterdayDate = new Date(currentYear, currentMonth, currentDay - 1); console.log(yesterdayDate.toLocaleDateString()); // Output: "2/27/2023" (if today is 2/28/2023)
In this example, we first create a new
Date object for the current date using the
Date() constructor without any arguments, which creates a
Date object for the current date and time.
We then get the year, month, and day of the current date using the
getDate() methods on the
Next, we create a new
Date object for yesterday’s date by passing in the
currentDay - 1 as arguments to the
Date() constructor. This subtracts 1 from the current day to get yesterday’s date.
Finally, we can use the
toLocaleDateString() method on the
yesterdayDate object to get yesterday’s date as a string in the format of the user’s locale. In this example, if today is February 28th, 2023, the output will be “2/27/2023”.