How to Get Yesterday’s Date Using JavaScript
Do you need to get yesterday’s date using JavaScript? In this blog post, we will guide you through the steps to achieve this.
To get started, you need to obtain the current date and then subtract one day from it. Here is an example code snippet:
1 | const today = new Date(); |
In the above code, we create a Date
object today
to represent the current date. Then we create another Date
object yesterday
and set it to the value of today
. By calling the setDate()
method on yesterday
and passing yesterday.getDate() - 1
as the parameter, the value of yesterday
is set to the previous day.
Even if it is the first day of the month, JavaScript handles this logic correctly and points to the last day of the previous month.
By running this code, you will see the today’s date and yesterday’s date printed in the console.
Tags: JavaScript, Date manipulation