DEV Community

Cover image for Fetching Yesterday's Date in JavaScript: A Beginner's Guide
YURII DE.
YURII DE.

Posted on

1

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more