How to get current date and time in functional component in React.js?

How to use class based components in React.js? »

In this section you’re going to learn how to get user’s current time and get hours from the time. You’re also going to simulate an API, such that it’d look like it takes 3 seconds to get the current hour in your time zone. Write the following code inside index.js file:

import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
    const getHours = () => {
       const currentHours = new Date().getHours();
       return currentHours;
    }

    setTimeout(() => {const hours = getHours(); console.log(hours);}, 3000);

    return <div>
       Hello World!
    </div>;
};


ReactDOM.render(
 <App />,
 document.querySelector('#root')  
);

In the above file, inside the App component, you’ve defined a function named getHours() which gives you current hour of the day (without minutes). Later, this function is being called inside the setTimeout() function. setTimeout() is a Javascript function that takes in two parameters. The first parameter is a function and the second parameter takes time duration in milliseconds. The first function is called after the duration of time defined in the second parameter. Therefore, in this case, the function () => {const hours = getHours(); console.log(hours);} is called after 3 seconds, thus simulating an API request (which often takes some time to get the results from a network request).

Close the server by pressing Ctrl + C from Terminal / CMD and restart it with npm start

Open the console window with Ctrl + Shift + K and now you should be able to see the active hours after 3 seconds.

Leave a Comment