Clue Mediator

How to get yesterday's, today's, and tomorrow's date using JavaScript

šŸ“…January 2, 2021
šŸ—JavaScript

In this short article, weā€™ll explain to you how to get yesterdayā€™s, todayā€™s, and tomorrowā€™s date using Javascript. Using the Date object, we can easily calculate the date in JavaScript.

JavaScript has a built-in Date object that represents the current date and time. First, we will get the current date (Today) and then after we can get the date of yesterday and tomorrow.

Get yesterday's, today's, and tomorrow's date using JavaScript

  1. Get todayā€™s date
  2. Get yesterdayā€™s date
  3. Get tomorrowā€™s date

1. Get todayā€™s date

As we mentioned, we will get today's date using the date object as shown below in the code. We will use the `toDateString()` method to convert the date into a readable string.

let dt = new Date();
console.log(dt);
// Sat Jan 02 2021 13:12:35 GMT+0530 (India Standard Time)

dt = dt.toDateString();
console.log(dt);
// Sat Jan 02 2021

2. Get yesterdayā€™s date

To calculate yesterday's date, first we have to get the current date (today) then subtract 1 day from the date.

let today = new Date();
let yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
console.log(yesterday.toDateString());
// Fri Jan 01 2021

Here, we have used the `getDate()` function to get the day of the date. After subtracting one day from the date, use the `setDate()` function to set yesterday's date into the date object.

3. Get tomorrowā€™s date

Same way, we can easily calculate the tomorrowā€™s date. Here, we add 1 day in the current date.

let today = new Date();
let tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(tomorrow.toDateString());
// Sun Jan 03 2021

I hope you find this article is helpful.
Thank you for reading. Happy Coding..!! šŸ™‚