DayJS 格式秒、分钟和小时

zlo*_*tte 4 javascript

hours minutes seconds我想在获取diff值时进行格式化dayjs

这是我的代码:

    newAppoint.occupied.push({
        hours: dayjs().diff(user.appointment, 'hour'),
        minutes: dayjs().diff(user.appointment, 'minute'),
        seconds: dayjs().diff(user.appointment, 'second')
    });
Run Code Online (Sandbox Code Playgroud)

现在的问题是我得到了像 一样的差异0 hrs 3 min 228 sec

我怎样才能把它变成这样的东西:00 hrs 03 min 59 sec

我尝试在push函数之后添加此代码:

    dayjs(newAppoint.occupied.hours).format('hh');
    dayjs(newAppoint.occupied.minutes).format('mm');
    dayjs(newAppoint.occupied.seconds).format('ss');
Run Code Online (Sandbox Code Playgroud)

但这没有什么区别。

Nat*_*son 9

diff 函数返回总秒数、分钟数或小时数,而不是组成部分。

尝试这个:

totalSeconds = dayjs().diff(user.appointment, 'second');

totalHours = Math.floor(totalSeconds/(60*60))  // How many hours?
totalSeconds = totalSeconds - (totalHours*60*60) // Pull those hours out of totalSeconds

totalMinutes = Math.floor(totalSeconds/60)  //With hours out this will retun minutes
totalSeconds = totalSeconds - (totalMinutes*60) // Again pull out of totalSeconds
Run Code Online (Sandbox Code Playgroud)

然后你就得到了三个带有你需要的值的变量:totalHours totalMinutestotalSeconds