In ReactJS, you can get the current date using JavaScript’s built-in Date object. Here’s an example of how you can do this:
import React, { useState, useEffect } from 'react';
function App() {
const [currentDate, setCurrentDate] = useState(new Date());
useEffect(() => {
const interval = setInterval(() => {
setCurrentDate(new Date());
}, 1000); // Update every second
return () => clearInterval(interval); // Clean up the interval on unmount
}, []);
return (
<div>
<p>Current Date: {currentDate.toLocaleString()}</p>
</div>
);
}
export default App;
In this example, we’re using the useState hook to manage the state of the current date. We use the useEffect hook to set up an interval that updates the state every second using the setInterval function. The returned cleanup function from useEffect clears the interval when the component unmounts, preventing memory leaks.
The toLocaleString() method is used to format the currentDate as a human-readable string. You can adjust the formatting to your preference using other Date methods or third-party libraries like date-fns if needed.
