js中时间的处理,不借助于moment/dayjs这样的工具库,原生获取格式化的时间,最简单的实现方式可以参考下面这样。
实现效果
代码实现
- 封装hooks
import { useState, useEffect } from "react";
export function useCountTime() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const timer = setInterval(() => {
setTime(new Date());
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
return formatDate(time);
}
function formatDate(date) {
return date.toLocaleString("zh-cn", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
});
}
- 使用
import { useCountTime } from "../../components/TimeCount";
...
const time = useCountTime()
return (
<>
<h3>今天是星期 {time}</h3>
</>
)
鲜为人知的内置时间格式化
function formatDate(date) {
return new Intl.DateTimeFormat("zh-CN", {
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
}).format(date);
}
福利推送
文档参考链接:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
有兴趣的可以去了解下
鼠标移动坐标
- 封装鼠标移动坐标的hooks
import { useState, useEffect } from "react";
export function useMouse() {
const [mouse, setMouse] = useState({ x: 0, y: 0 });
function handleMouseMove(event) {
setMouse({ x: event.clientX, y: event.clientY });
}
useEffect(() => {
window.addEventListener("mousemove", handleMouseMove);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
};
}, []);
return mouse;
}
import { useMouse } from "../../hooks/userMouse";
const { x, y } = useMouse();
return (
<>
<div>
x:{x} y:{y}
</div>
</>
)