DEV Community

Cover image for Fetching Yesterday's Date in JavaScript: A Beginner's Guide
YURIIDE
YURIIDE

Posted on

Fetching Yesterday's Date in JavaScript: A Beginner's Guide

Fetching Yesterday's Date in JavaScript: A Beginner's Guide

DEMO👀

Handling dates is a fundamental part of web development. One common task you might face is getting yesterday's date. This article will guide you through the process in JavaScript, ensuring clarity and simplicity.

To start, JavaScript's Date object is your go-to for date-related operations. Here’s a quick way to get yesterday’s date:

  1. Create Today's Date Object: let today = new Date();
  2. Get Yesterday's Date: Subtract one day from today's date using setDate() and getDate().
let today = new Date(); // Today's date
let yesterday = new Date(today); // Copy today's date
yesterday.setDate(yesterday.getDate() - 1); // Subtract one day
Enter fullscreen mode Exit fullscreen mode

This code snippet makes a copy of today's date and adjusts it to represent yesterday by subtracting one from the current day.

To display it, you might want to format it nicely:

console.log(yesterday.toDateString()); // E.g., "Mon Mar 21 2022"
Enter fullscreen mode Exit fullscreen mode

This straightforward method allows you to manipulate and display yesterday's date, a handy trick for various web development scenarios.

Top comments (0)