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 (
<div>
<p>Yesterday's date: {yesterdayDate}</p>
</div>
);
}
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
.