Have you worked on a project and you wanted to display the date and time live maybe in your navbar or something?
Seems like a long shot? you will be surprised to know it is not,
If you are creating a system for a company - a bank in my case, a school or a hospital, you will find yourself in need of that little trick
But who needs a clock, there's one in every Pc and mobile phone right? well sometimes websites like to fancy themselves right
So let's just get into it
We will start by cloning the small demo I have already created for you
In your terminal make sure you are in the right directory and run those following lines
First Step: Clone the repo in your directory
git clone https://github.com/AhmedSarhan/live-watch.git
Now you should have a basic CRA with some additional styles and icons as follow:
The code should look like this
import './App.css';
import { ReactComponent as ClockIcon } from './icons/clock.svg';
import { ReactComponent as CalenderIcon } from './icons/calendar.svg';
function App() {
return (
<div className="App">
<CalenderIcon />
<p>date</p>
<ClockIcon />
<p>time</p>
</div>
);
}
export default App;
As you can see a basic React app function component with just the two icons and the styles we need imported and applied
In this article we will change those two p tags with real time date and time using only Js and React Hooks
Second Step: move to the project directory
cd live-watch
Third Step: Install npm packages the repo in your directory
npm i
Fourth Step: Run the application
This step should open your localhost on port 3000 by default
Your website should look like this
Now let's get to work
First of all make sure to import React and both useState, useEffect hooks at the top of your app component with the following line of code:
import React, {useState, useEffect} from 'react';
Now we are set to do the magic
Create our app state
We are going to make a dateState using the useState hook as follow:
const [dateState, useDateState] = useState(new Date())
;
Now by default the dateState initial value will be right now date but it won't update unless the user reloads the page so we need to work with that ... But first let's show the date to the user
Displaying the Date and Time
As you can see all the user can see is 📆 Date 🕒 Clock
But won't it be better to show the user the real date and time;
So there are many ways to do this but since this is a small application I would like to do it all in one state hook
<div className="App">
<CalenderIcon />
<p>
{' '}
{dateState.toLocaleDateString('en-GB', {
day: 'numeric',
month: 'short',
year: 'numeric',
})}
</p>
<ClockIcon />
<p>
{dateState.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true,
})}
</p>
</div>
So this is how your app should look like right now
as you can see using toLocalString JavaScript method which is a standard built in object in JavaScript, we can change the date of this moment to view it in a variety of ways
As you can see in the first paragraph tag I am using toLocalString to view the date of today in the format D MMM YYYY
which should show on the date of this article release 5 Jun 2021
In the second paragraph, I'm displaying the time of this moment in the format h:mm a
using the 12 hour system
Of course there are variety of ways to display the same date and you can play around with toLocalString method more and find a bit more of them.
Now we have made it two thirds of the way, the user can see the time and date of right now, but I bit it's not exactly right now any more, I would bet it is a minute or two late from your devices watch unless your refresh the page.
This leads us to our final step
Making Our watch Real-Time
In this step we will use the second hook we imported at the beginning of this article; the useEffect hook;
We will make the magic happen with one simple line of code:
useEffect(() => {
setInterval(() => setDateState(new Date()), 30000);
}, []);
Now in this useEffect, we update the date every 30000 milliseconds which means that the dateState useState hook will be updated every half a minute 30 seconds and our app will rerender the DOM accordingly
Now if you take a look at your app and wait for one minute to pass, you should see the clock updated smoothly just like your native device watch.
It might be a long wait, but it's worth it 😂🔥
Conclusion
Now your final app component code should look something like that
import React, { useState, useEffect } from 'react';
import './App.css';
import { ReactComponent as ClockIcon } from './icons/clock.svg';
import { ReactComponent as CalenderIcon } from './icons/calendar.svg';
function App() {
const [dateState, setDateState] = useState(new Date());
useEffect(() => {
setInterval(() => setDateState(new Date()), 30000);
}, []);
return (
<div className="App">
<CalenderIcon />
<p>
{' '}
{dateState.toLocaleDateString('en-GB', {
day: 'numeric',
month: 'short',
year: 'numeric',
})}
</p>
<ClockIcon />
<p>
{dateState.toLocaleString('en-US', {
hour: 'numeric',
minute: 'numeric',
hour12: true,
})}
</p>
</div>
);
}
export default App;
You can also compare your code to the final result of mine through the Final branch on the same GitHub repo
Top comments (1)
Very helpful post. One question, how do I make the seconds change in real-time? I added
second: 'numeric'
and it shows the seconds but they do not change and when I refresh the page sometimes it shows an error saying Error: Text content does not match server-rendered HTML.