import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
dayjs.extend(duration);
let timeOut = null
const setCountdown = ()=>{
if (timeOut){
clearTimeout(timeOut);
timeOut = null;
}
timeOut = setTimeout(()=>{
diffTime();
setCountdown();
},1000)
}
const diffTime = (targetTime = '2024-06-03 23:59:59')=>{
targetTime = dayjs(targetTime);
const diffNow = targetTime.diff(dayjs(), 'dates');
const durationTime = dayjs.duration(diffNow);
const hours = durationTime.get('hours');
const minutes = durationTime.get('minutes');
const seconds = durationTime.get('seconds');
const days = targetTime.diff(dayjs(), 'days');
let str = `${padNumber(hours)}:${padNumber(minutes)}:${padNumber(seconds)}`;
if (days > 0) {
str = `${days}天 ` + str;
}
return str
}
const padNumber = (num, length = 2) => (Array(length).join('0') + num).slice(-length);
个人开发记录,有错误请指正