gpt4 book ai didi

javascript - 如何在 React JS 中实时显示时间和日期?

转载 作者:行者123 更新时间:2023-12-03 21:11:54 31 4
gpt4 key购买 nike

简报:
嗨,我创建了一个 Hook useDate()显示当前时间和日期,如下所示:

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' })}\n\n`;

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,
};
};
我在我的 中使用它组件 如下:
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>
);
};
应用程序中的日期/时间格式:
8 月 2 日,星期日
晚上 11:54
问题陈述:
目前发生的情况是日期和时间直到我 才更新。刷新 这页纸。有什么方法可以在 中更新以下所有内容实时 ?
我正在考虑使用 每 1 分钟后的间隔 计算更新的时间和日期,但不知道这是否是个好主意。我也不知道如何开始,间隔将如何 清除 ?
谢谢! :)

最佳答案

由于您可以在自定义 Hook 中使用 Hook ,因此您可以创建一个间隔来更新每分钟,如下所示:


export const useDate = () => {
const locale = 'en';
const [today, setDate] = React.useState(new Date()); // Save the current date to be able to trigger an update

React.useEffect(() => {
const timer = setInterval(() => { // Creates an interval which will update the current data every minute
// This will trigger a rerender every component that uses the useDate hook.
setDate(new Date());
}, 60 * 1000);
return () => {
clearInterval(timer); // Return a funtion to clear the timer so that it will stop being called on unmount
}
}, []);

const day = today.toLocaleDateString(locale, { weekday: 'long' });
const date = `${day}, ${today.getDate()} ${today.toLocaleDateString(locale, { month: 'long' })}\n\n`;

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,
};
};

关于javascript - 如何在 React JS 中实时显示时间和日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63219753/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com