display time in react

Solutions on MaxInterview for display time in react by the best coders in the world

showing results for - "display time in react"
Leona
26 Feb 2018
1export const useDate = () => {
2  const locale = 'en';
3  const [today, setDate] = React.useState(new Date()); // Save the current date to be able to trigger an update
4
5  React.useEffect(() => {
6      const timer = setInterval(() => { // Creates an interval which will update the current data every minute
7      // This will trigger a rerender every component that uses the useDate hook.
8      setDate(new Date());
9    }, 60 * 1000);
10    return () => {
11      clearInterval(timer); // Return a funtion to clear the timer so that it will stop being called on unmount
12    }
13  }, []);
14
15  const day = today.toLocaleDateString(locale, { weekday: 'long' });
16  const date = `${day}, ${today.getDate()} ${today.toLocaleDateString(locale, { month: 'long' })}\n\n`;
17
18  const hour = today.getHours();
19  const wish = `Good ${(hour < 12 && 'Morning') || (hour < 17 && 'Afternoon') || 'Evening'}, `;
20
21  const time = today.toLocaleTimeString(locale, { hour: 'numeric', hour12: true, minute: 'numeric' });
22
23  return {
24    date,
25    time,
26    wish,
27  };
28};