PASSWORD RESET

Your destination for complete Tech news

How to get yesterday’s date in Javascript?

689 0
< 1 min read

You can get yesterday’s date in JavaScript by creating a new 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 getFullYear(), getMonth(), and getDate() methods on the currentDate object.

Next, we create a new Date object for yesterday’s date by passing in the currentYear, currentMonth, and 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”.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.