How to get the current date in React
In this tutorial, we are going to learn about how to access the current date in a react app.
Using new Date() constructor
We can use the new Date()
constructor to get the current date in a react component.
The new Date()
constructor creates a new date instance that contains the following methods to construct the full date.
getDate() method: It returns the day of the month.
getMonth() method: It returns the month of a year, where 0 is January and 11 is December.
getFullYear() method: It returns the year in four-digit format (YYYY).
Example:
import React from "react";
export default function App() {
const current = new Date();
const date = `${current.getDate()}/${current.getMonth()+1}/${current.getFullYear()}`;
return (
<div className="App">
<h1>Current date is {date}</h1> </div>
);
}
Output: