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

新手上路,请多包涵

简报:

嗨,我创建了一个钩子 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 分钟后使用一个时间间隔 来计算更新的时间和日期,但我真的不知道这是否是个好主意。我也不知道如何开始以及如何 清除 间隔?

谢谢! :)

原文由 Vinay Sharma 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

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


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

原文由 Domino987 发布,翻译遵循 CC BY-SA 4.0 许可协议

我有一个想法。我将循环 while 和动态睡眠之间的区别 currentTimecurrentTime + 1 second 的秒数舍入。你可以参考这个脚本。

 function getRealTime() {
  const currentTime = Date.now();
  console.log(new Date(Math.round(currentTime / 1000) * 1000), currentTime);
  return (Math.floor(currentTime / 1000) + 1) * 1000 - currentTime;
}

(async function () {
  let reduceTime = 0;
  while (true) {
    reduceTime = getRealTime();
    await sleep(reduceTime);
  }
})()

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

原文由 T PH KH 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题