Code on how to get Yesterday date in JavaScript
This article is about how to get yesterday's date in JavaScript. We will get current date using new Date() and the substract one day from it.
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:
Related Posts
Get Tomorrow's Date using JavaScript - Quick Way
Tutorial on how to get tomorrow's date using JavaScript and momentjs library
Convert date to long date format using Javascript
Learn how to convert a date to a long date format using Javascript. To convert it to a long format we will be using a toLocaleDateString() method in javascript.
Fix error:0308010C:digital envelope routines::unsupported
Learn to solve the "Error: error:0308010C:digital envelope routines::unsupported" error in Node.js application (Vue, Angular or react) using the solutions in this article.
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
