how to get yesterday date in javascript

Getting yesterday’s date in JavaScript is a common task that can be accomplished using the Date object. The Date object in JavaScript represents a single moment in time, and it can be used to perform various date-related operations, including getting the current date and time, setting a specific date and time, and performing arithmetic on dates.

Here are three common methods to get yesterday’s date in JavaScript:

Using setDate method:

The setDate method in JavaScript can be used to set the day of the month for a Date object. To get yesterday’s date, you can create a new Date object for the current date and time, and then use the setDate method to subtract one day from the current date. For example:

how to get yesterday date in javascript
how to get yesterday date in javascript

In this example, the today variable is set to a new Date object representing the current date and time. The yesterday variable is set to a new Date object equal to today by passing today as an argument to the Date constructor. The setDate method is then used to subtract one day from the current date by passing yesterday.getDate() – 1 as the argument.

Using setUTCDate method:

The setUTCDate method in JavaScript can be used to set the day of the month for a Date object in Universal Time (UTC). To get yesterday’s date in UTC, you can create a new Date object for the current date and time in UTC, and then use the setUTCDate method to subtract one day from the current date. For example:

how to get yesterday date in javascript
how to get yesterday date in javascript

In this example, the today variable is set to a new Date object representing the current date and time. The yesterday variable is set to a new Date object representing yesterday’s date in UTC by passing the year, month, and day of the current date minus one day to the Date.UTC method. The Date.UTC method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC for the specified date and time, which can be passed to the Date constructor to create a new Date object.

Using getTime method:

The getTime method in JavaScript can be used to get the number of milliseconds since January 1, 1970, 00:00:00 UTC for a Date object. To get yesterday’s date, you can create a new Date object for the current date and time, and then use the getTime method to subtract one day worth of milliseconds from the current date. For example:

how to get yesterday date in javascript
how to get yesterday date in javascript

By umarbwn