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:
-
Create Today's Date Object:
let today = new Date();
-
Get Yesterday's Date: Subtract one day from today's date using
setDate()
andgetDate()
.
let today = new Date(); // Today's date
let yesterday = new Date(today); // Copy today's date
yesterday.setDate(yesterday.getDate() - 1); // Subtract one day
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"
This straightforward method allows you to manipulate and display yesterday's date, a handy trick for various web development scenarios.