Your destination for complete Tech news

How to get yesterday’s date in React JS?

354 0
< 1 min read

You can get yesterday’s date in React using the JavaScript Date object. Here’s how you can do it:

import React from 'react';

function YesterdayDate() {
  const getYesterdayDate = () => {
    const today = new Date();
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    return yesterday.toISOString().split('T')[0];

  const yesterdayDate = getYesterdayDate();

  return (
      <p>Yesterday's date: {yesterdayDate}</p>

export default YesterdayDate;

In this example, the getYesterdayDate function creates a new Date object for today, then creates another Date object for yesterday by subtracting one day from the current date using setDate(). After that, it formats the yesterday’s date as an ISO string and extracts the date part using split('T')[0].

This will give you yesterday’s date in the format “YYYY-MM-DD”. You can adjust the formatting based on your needs.

Remember that JavaScript’s Date object works in the local time zone of the user’s device. If you need to handle time zones or more complex date manipulations, consider using a library like date-fns or moment.js.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.