实现原理
通过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>
)
}