How to get yesterday’s, today’s, and tomorrow’s date using 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
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.
1 2 3 4 5 6 7 | 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.
1 2 3 4 5 | 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.
1 2 3 4 5 | 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..!! 🙂