How to get yesterday’s date using JavaScript

It is very simple!

Find today’s date and subtract by one to get yesterday’s date.

Here is the code:

const today = new Date();
const yesterday = new Date();
yesterday.setDate(today.getDate() - 1);

console.log('Today\'s date & time: ', today);
console.log('Yesterday\'s date & time: ', yesterday);
console.log('Today\'s date: ', today.toDateString());
console.log('Yesterday\'s date: ', yesterday.toDateString());
console.log('Today\'s Epoch time: ', today.getTime());
console.log('Yesterday\'s Epoch time: ', yesterday.getTime());


Today's date & time:  2022-03-12T17:45:29.734Z
Yesterday's date & time:  2022-03-11T17:45:29.734Z

Today's date:  Sat Mar 12 2022
Yesterday's date:  Fri Mar 11 2022

Today's Epoch time:  1647107129734
Yesterday's Epoch time:  1647020729734

new Date() will fetch the current date and time. Pass it to setDate() function along with minus 1 to fetch today’s date. You can use setUTCHours() and pass 0 to set the time 0.

today.setUTCHours(0, 0, 0, 0);
Today's date & time:  2022-03-12T00:00:00.000Z
Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.