Solution
To add days in date in React, you can use date
setDate()
method it will add days as per your desired number.
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 add 3 days in date.
// Get the current date
let currentDate = new Date();
// Add 3 days to the current date
currentDate.setDate(currentDate.getDate() + 3);
console.log(currentDate); // Outputs the date 3 days in the future
Example
In this example, we will add 1 day in current date to get tomorrow date.
Let’s start coding…
import React, { useEffect, useState } from "react";
export default function App() {
const [tomorrowDate, setTomorrowDate] = useState("");
useEffect(() => {
// Get the current date
let currentDate = new Date();
// Add 3 days to the current date
currentDate.setDate(currentDate.getDate() + 3);
setTomorrowDate(currentDate.toLocaleDateString());
}, []);
return (
<div className="App">
<h1>{`Tomorrow Date`}</h1>
<p>{tomorrowDate}</p>
</div>
);
}
Output