typescript 如何在momentjs中格式化Duration

ohtdti5x  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(124)

我做了一个倒计时钟,它能显示离某个时刻还有多少年、月、日、时、分和秒。
我只是有一个小问题的解决方案,这应该是显而易见的,但我就是想不通我的生活。我如何格式化来自timeBetween.hours()和timeBetween.seconds()的数据?我需要它们总是2位数格式,但默认情况下,如果一个数字小于10,它不会用另一个零填充。
format()函数不能处理duration。我找到了一个解决方法,格式化moment(timebetween)._data,但是我有一个月的时间,因为它变成了基于索引的。
代码如下:

const Clock = () => {
const [clock, setClock] = useState(moment());

const theEnd = moment('2050-01-01 00:00:00');
const timeBetween = moment.duration(theEnd.diff(clock));

useEffect(() => { setInterval(() => setClock(moment()), 1000)}, []);

return (
    <div className="clock-container">
        <p className='time'>{`${timeBetween.years()} years, ${timeBetween.months()} months, ${timeBetween.days()} days`}</p>
        <p className='time'>{`${timeBetween.hours()} hours : ${timeBetween.minutes()} minutes : ${timeBetween.seconds()} seconds`}</p>
    </div>
);
};
export default Clock;
inb24sb2

inb24sb21#

我把它垫成这样。简单得让人无法抗拒。

const zeroPad = (num: number) => String(num).padStart(2, '0');

<div className="clock-container">
            <p className='time'>{`${timeBetween.years()} years, ${timeBetween.months()} months, ${timeBetween.days()} days`}</p>
            <p className='time'>{`${zeroPad(timeBetween.hours())} hours : ${zeroPad(timeBetween.minutes())} minutes : ${zeroPad(timeBetween.seconds())} seconds`}</p>
        </div>

相关问题