2022-06-28 20:36:06 +08:00

61 lines
1.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import dayjs from "dayjs"
import { useEffect, useRef, useState } from "react"
//倒计时hook
export const useTimeCountDown = () => {
const [showTime, setShowTime] = useState({
DD: '',
HH: '',
MM: '',
SS: ''
})
const [timeStatus, setTimeStatus] = useState<0|1|2>(0) //倒计时状体 0:倒计时未开始 1:倒计时中, 2倒计时已结束
const timeObj:any = useRef()
const endTime = useRef('')
const onStart = (val = '') => {
endTime.current = val
if(endTime.current) {
clearInterval(timeObj.current)
timeObj.current = setInterval(() => {
count_down()
}, 1000)
}
}
useEffect(() => {
return () => {
clearInterval(timeObj.current)
}
}, [])
const count_down = () => {
var startData = dayjs();
var endDate = dayjs(endTime.current);
setTimeStatus(() => 1)
if(startData >= endDate) {
clearInterval(timeObj.current)
setShowTime((e) => ({...e, DD:'00', HH:'00', MM:'00', SS:'00'}))
setTimeStatus(() => 2)
return false
}
var _dd = endDate.diff(startData,'day');
var _hh = endDate.diff(startData,'hour');
var _mm = endDate.diff(startData,'minute');
var _ss = endDate.diff(startData,'second');
// 转换
var hh = _hh - (_dd*24);
var mm = _mm - (_hh*60);
var ss = _ss - (_mm*60);
// 格式化
var DD = ('00'+_dd).slice(-2);
var HH = ('00'+hh).slice(-2);
var MM = ('00'+mm).slice(-2);
var SS = ('00'+ss).slice(-2);
// console.log('endTime::', `${DD}-${HH}-${MM}-${SS}`)
setShowTime((e) => ({...e, DD, HH, MM, SS}))
}
return {
showTime,
onStart,
timeStatus
}
}