Solution

To get yesterday’s date in React, you can use JavaScript’s built-in Date object. First, create a Date object for the current date and time using the new Date() constructor. Then, use the setDate() method to subtract one day from the date. This method takes the number of days to add or subtract as an argument, so to subtract one day you can pass in -1. Here is an example of how to do this:

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

new Date().setDate()

The setDate() method changes the day of the month of a given Date instance, based on local time.

new Date().getDate()

The getDate() method returns the day of the month for the specified date according to local time.

Snippet

In this snippet, we will create a date object and get a yesterday date from it.

const date = new Date();

date.setDate(date.getDate() - 1);

console.log(date.toDateString()) // Sun Nov 27 2022
console.log(date.toLocaleString()) // 11/27/2022, 8:52:43 PM

Example

In this example, we will show the yesterday date in the console and page in react js.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [yesterdayDate, setYesterdayDate] = useState("");

  useEffect(() => {
    const date = new Date();
    date.setDate(date.getDate() - 1);
    console.log(date.toDateString()); // Sun Nov 27 2022
    console.log(date.toLocaleString()); // 11/27/2022, 8:52:43 PM

    setYesterdayDate(date.toDateString());
  }, []);

  return (
    <div className="App">
      <h1>{`Yesterday Date`}</h1>
      <p>{yesterdayDate}</p>
    </div>
  );
}

Output

Current, Year

codesandbox