使用js写个数字时钟

两盒软妹~` 提交于 2020-02-08 17:29:08

实现原理

通过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>
  )
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!