Code on how to get Yesterday date in JavaScript

In this article we will learn how to get yesterday’s date in JavaScript.

To get the yesterday’s date we have to first get the current day date using new Date() method in JavaScript and then we subtract a day to get the previous day date.

Read about : How to Get Tomorrow’s Date Using JavaScript

Here, in this article we will get yesterday’s date using two solutions: Using vanilla JavaScript and using moment JS.

Solution 1 : Using Vanilla JavaScript

So the approach is get the current day date and then subtract one day from the it and set the yesterday date.

Example:

const today = new Date()
const yesterday = new Date(today)

yesterday.setDate(yesterday.getDate() - 1)
const yesterdayDate = yesterday.toDateString()

console.log(yesterdayDate)

Output:

Tue Nov 09 2021

Here,

new Date() : It give the current date and time of the day.

yesterday = new Date(today) : added the date on yesterday variable to change the day to yesterday’s using setDate().

setDate() : It lets us to change the day of the month at a given instance.

getDate() : This method extract the date of the month from the string returned by new Date(). Example: 2021-11-10T17:56:48 will return 10.

toDateString() : This method returns the date in a proper format in English. Example, from 2021-11-10T17:56:48 to Tue Nov 09 2021

Solution 2 : Using momentJs

MomentJs is an open-source JavaScript library which you can install in your project using npm. It removes the need to use the native JavaScript new Date() object.

You can just type moment().format("YYYY-MM-DD") to get the the current date with the correct format.

So to find yesterday’s date in JavaScript using momentJS, you can just type the following code.

moment().subtract(1, "days").format("YYYY-MM-DD");

Related Topics:

Current Date in Different Date Formats (mm-dd-yyyy)

Scroll to Top