In this article, we will learn how to simply display the current time in our ReactJs application. We will use Date() method. We will create a new object with Date(), which comes along with some predefined methods such as getMonth() that shows the month, getHour() shows the current hour, getTime() that shows in milliseconds the time is calculated from 1970 in case of getTime() and there are many more.
Prerequisite: Introduction and installation react
Creating React Application:
Step 1: Create the react project folder, for that open the terminal, and write the command npm create-react-app folder name, if you have already installed create-react-app globally.If you haven’t then install create-react-app globally by using the command npm -g create-react-app or can install locally by npm i create-react-app.
npm create-react-app project
Step 2: After creating your project folder(i.e. project), move to it by using the following command.
cd project
File Structure: It will look like this.
Example: In App.js let’s create a Date object, from the date object we get predefined methods getHours(), getMinutes(), and getSeconds() indicating the current hour, minute, and the seconds.
Javascript
// App.js function App() { const date = new Date(); const showTime = date.getHours() + ':' + date.getMinutes() + ":" + date.getSeconds(); return ( <div className= "App" > <h1 align= "center" >Current Time</h1> <h2 align= "center" > {showTime}</h2> </div> ); } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output:
The output shows the exact time at which the component renders, here it is showing 21 hours, 44 minutes, and 43 seconds that we achieved through date.getHours(), date.getMinutes(), and date.getSeconds() respectively, where the date is the object we have created.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date