How to Find Yesterday’s Date in Javascript

  • We have selected button and h1 elements using the document.querySelector() method and stored them in btnGet and result variables respectively.
  • We have attached the click event listener to the button element.
  • Inside the click event handler function, we are getting an instance of Date using Date constructor and storing it in the dateObj variable.
  • The Date instance have getDate() and setDate() methods. getDate() method returns current date and setDate() 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, and date by calling getMonth(), getFullYear(), and getDate() methods respectively of Date 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, and date variables and displaying it inside the h1 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}`;
});