Hello, React developers! In this tutorial, we'll explore how to get the current date and time in ReactJS with different formats. We'll cover several examples that demonstrate how to display the current date and time using different formats such as "MM/DD/YYYY", "YYYY-MM-DD HH:mm:ss", and more.
Set Up a New React Project
If you don't have a React project yet, you can create one using Create React App (CRA). Open your terminal and run the following command:
npx create-react-app react-date-time-example
Create a New Component
Now, let's create a new component called DateTime
that will display the current date and time in different formats. Create a file named DateTime.js
in the src
directory of your React project:
// src/DateTime.js
import React, { useState, useEffect } from 'react';
const DateTime = () => {
const [currentDateTime, setCurrentDateTime] = useState('');
useEffect(() => {
// Update the current date and time every second
const interval = setInterval(() => {
const now = new Date();
setCurrentDateTime(now);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div>
<h2>Current Date and Time</h2>
<p>{currentDateTime.toLocaleString()}</p>
<p>{currentDateTime.toISOString()}</p>
<p>{currentDateTime.toLocaleDateString()}</p>
<p>{currentDateTime.toLocaleTimeString()}</p>
</div>
);
};
export default DateTime;
Render the Component in App.js
Now, let's render the DateTime
component in the App.js
file. Open the App.js
file in the src
directory and update it as follows:
// src/App.js
import React from 'react';
import DateTime from './DateTime';
function App() {
return (
<div>
<h1>React Date and Time Example</h1>
<DateTime />
</div>
);
}
export default App;
Test the Application
Start your React development server by running the following command in your project's root directory:
npm start
Visit http://localhost:3000
in your web browser. You should now see the "Current Date and Time" heading and the current date and time displayed in different formats.
Congratulations! 🎉 You've successfully displayed the current date and time in React with different formats.
Feel free to customize the formats further based on your requirements or explore other date and time formatting options available in JavaScript.
Here are a few additional formatting examples you can try:
<p>{currentDateTime.toDateString()}</p>
<p>{currentDateTime.toUTCString()}</p>
<p>{currentDateTime.toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}</p>
With this knowledge, you can now work with dates and times in your React applications and display them in various formats according to your needs.
Happy coding, and enjoy building awesome React applications with date and time functionalities!