How to get yesterday date and tomorrow date in JavaScript

#javascript #date

Last updated on May 24, 2021 by Suraj Sharma



In this tutorial, you’ll learn how to get yesterday’s date and tomorrow's date using vanilla JavaScript Date object.



Get Yesterday's Date


To get yesterday’s date, we will follow the following steps:


1) Get the current timestamp in milliseconds using Date object getTime() method,


const timeStamp = new Date().getTime();

2) Convert 24 hours to milliseconds and subtract it from the current timestamp.,


const yesterdayTimeStamp = timeStamp - 24*60*60*1000;

3) Finally, initialize new Date() constructor with yesterdayTimeStamp


const yesterdayDate = new Date(yesterdayTimeStamp);


Here’s the complete code in Vanilla JavaScript


function getYesterdayDate() {
  return new Date(new Date().getTime() - 24*60*60*1000);
}

console.log(getYesterdayDate());


Get Tomorrow's Date


Similary, we can get tomorrow's date by adding 24 hours to the current timestamp, for example


function getTomorrowDate() {
  return new Date(new Date().getTime() + 24*60*60*1000);
}

console.log(getTomorrowDate());


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.