How to get yesterday date of yesterday in JavaScript

In this article, we will see how to get the date of yesterday in JavaScript. To understand, we should know about JavaScript date objects and also functions like getDate() and setDate() to get our output.

new Date(): Creates a date object with the current time and object.

getDate(): It fetches the day of the month.

setDate(): We can use this function to set the day of the month.

Example:

const today = new Date()
const yesterday=new Date()
yesterday.setDate(today.getDate() - 1)
console.log(yesterday)

Output:

2022-12-09T20:58:21.917Z

Here, we created a date object and stored it in today’s variable. Then we use the getDate() method to get the day of the month and subtract it with 1 so that we get the date of yesterday. Then we use the setDate() method on yesterday’s variable, passing the current day minus one as the parameter to achieve our output.

As you can see along with the date we have got some other time elements.

To get only the date with month and year we can do the below:

const today = new Date()
const yesterday=new Date()
yesterday.setDate(today.getDate() - 1)
console.log(yesterday)



console.log(yesterday.getDate()) // Just to check if the dd is correct
console.log(yesterday.getFullYear()) // It's the Year
console.log(yesterday.toLocaleString('default', { month: '2-digit' })) //It's the month

//Full date below, we need to concatenate those
console.log(yesterday.getFullYear()+"-"+yesterday.toLocaleString('default', { month: '2-digit' })+"-"+yesterday.getDate())

Now you may think that what I just created is just a string and obviously you are right.

But we can easily convert a string to a date object in JavaScript.

We can use the below code instead of :¬† ¬†yesterday.toLocaleString(‘default’, { month: ‘2-digit’ })

yesterday.getMonth()+1

We are using +1 as the result of .getMonth starts with 0.

So for January, it will show 0 and for December it will show 11.

Leave a Reply

Your email address will not be published. Required fields are marked *