23-02-21
小于 1 分钟
实时刷新直播时长
import moment from 'moment';
import {useState} from 'react'
//timestart值的格式 2023-09-23 12:03
function Time (timestart: string) {
const [now, setNow] = useState(Number)
const timelive = () => {
//转化为unix时间戳
let timestartunix = moment(timestart);
let timenow = moment().format('YYYY-MM-DD HH:mm:ss') ;
//把时间戳相差的值转为秒
const live =(moment(timenow).diff(moment(timestartunix),'seconds' ));
setNow(live);
}
//实时更新 1000ms
setInterval(timelive, 1000);
//当数字只有一位时补零 1=>01
//{now%60 <= 9 ? "0" + now%60 : now%60}秒
return (
<div >
直播时长:{Math.floor(now/3600) <= 9 ? "0" + Math.floor(now/3600) :Math.floor(now/3600)}小时{Math.floor((now/60)%60) <= 9 ? "0" + Math.floor((now/60)%60) : Math.floor((now/60)%60)}分钟{now%60 <= 9 ? "0" + now%60 : now%60}秒
</div>
)
}
注意变量的类型要统一
<div>
{Time(data.live_time)}
</div>
Powered by Waline v2.14.4