使用js写个数字时钟

实现原理

通过Date对象获取当前计算机的系统时间,注册计时器每隔一秒重新获取时间即可

格式化时间

  function setTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();
    const hour = now.getHours();
    const minute = now.getMinutes();
    const second = now.getSeconds();
    return `${year}年${month}月${date}日 ${hour}:${minute}:${second < 10 ? '0' + second : second}`
  }

这里简单地给秒钟显示时补个零

效果

在这里插入图片描述

完整代码

import React, { useEffect, useState } from 'react';

export default () => {

  const [now, setNow] = useState(setTime())

  useEffect(() => {
    const timer = setInterval(() => {
      const now = setTime();
      setNow(now);
    }, 1000);

    return () => {
      if (timer) {
		clearInterval(timer)
      }
    }
  }, [])

  function setTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const date = now.getDate();
    const hour = now.getHours();
    const minute = now.getMinutes();
    const second = now.getSeconds();
    return `${year}年${month}月${date}日 ${hour}:${minute}:${second < 10 ? '0' + second : second}`
  }

  return (
    <div>
         time: {now}
   </div>
  )
}
发布了20 篇原创文章 · 获赞 0 · 访问量 313

猜你喜欢

转载自blog.csdn.net/qq_40278455/article/details/104221635