96
rated 0 times
[
102]
[
6]
/ answers: 1 / hits: 37193
/ 4 Years ago, sun, august 2, 2020, 12:00:00
Briefing:
Hi, I have created a hook useDate()
to display current time and date as follows:
interface ReturnDate {
time: string;
date: string;
wish: string;
}
export const useDate = (): ReturnDate => {
const locale = 'en';
const today = new Date();
const day = today.toLocaleDateString(locale, { weekday: 'long' });
const date = `${day}, ${today.getDate()} ${today.toLocaleDateString(locale, { month: 'long' })}nn`;
const hour = today.getHours();
const wish = `Good ${(hour < 12 && 'Morning') || (hour < 17 && 'Afternoon') || 'Evening'}, `;
const time = today.toLocaleTimeString(locale, { hour: 'numeric', hour12: true, minute: 'numeric' });
return {
date,
time,
wish,
};
};
And I'm using it in my component below as follows:
const ProfileGreetings: FC = () => {
const { firstName } = useUserDetails();
const { date, time, wish } = useDate();
return (
<div className="greetings-container">
<h1>
{wish}
<PrimaryText text={`${firstName || ''}!`} />
</h1>
<div>
<h3>
{date}
<br />
{time}
</h3>
</div>
</div>
);
};
Date/Time format in app:
Sunday, 2 August
11:54 PM
Problem Statement:
Currently what's happening is that the date and time don't update until I refresh the page. Is there any way to have all of the following to be updated in real time?
I am thinking to use an interval after every 1 minute to compute the updated time and date, but don’t really know if that's good idea. Neither do I know how to start with that and how will the interval be cleared?
Thanks! :)
More From » reactjs