July 1, 2020
How to Find Yesterday’s Date in Javascript
- We have selected
button
andh1
elements using thedocument.querySelector()
method and stored them inbtnGet
andresult
variables respectively. - We have attached the
click
event listener to thebutton
element. - Inside the
click
event handler function, we are getting an instance ofDate
usingDate
constructor and storing it in thedateObj
variable. - The
Date
instance havegetDate()
andsetDate()
methods.getDate()
method returns current date andsetDate()
method set the date. - We are storing the current date in the
current
variable. - We are subtracting 1 from it and passing it to the
setDate()
method to set the date to yesterday’s date. - We are getting
month
,year
, anddate
by callinggetMonth()
,getFullYear()
, andgetDate()
methods respectively ofDate
instance.getMonth()
method returns an integer between 0 and 11, where January is 0, February is 1, and so on. That’s why we are adding 1 to a month to get the correct digit for the month. - We are simply creating a template string with
month
,year
, anddate
variables and displaying it inside theh1
element.
let btnGet = document.querySelector('button'); let result = document.querySelector('h1'); btnGet.addEventListener('click', () => { let dateObj = new Date(); let current = dateObj.getDate(); dateObj.setDate(current-1); let month = dateObj.getMonth() + 1; let date = dateObj.getDate() ; let year = dateObj.getFullYear(); result.innerText = `${month}/${date}/${year}`; });
In this tutorial, you will learn how to find yesterday’s date in javascript. The simplest way to find yesterday’s date is by using the
Date
constructor. After initialization, theDate
constructor returns theDate
object and there is no direct method available in theDate
object to grab yesterday’s date but with some minor calculation, we can get that.In the following example, we have one
button
and oneh1
element. Upon click ofbutton
, we simply want to get yesterday’s date and display it inside theh1
element. Please have a look over the code example and steps given below.HTML & CSS
div
,button
, andh1
). Thediv
element is just a wrapper for the rest of the elements.“Get”
and for the h1 element is“Result”
.style.css
stylesheet inside thehead
element.script.js
with ascript
tag at the bottom.Javascript