首页 > 解决方案 > DayJS 格式秒分钟和小时

问题描述

hours minutes seconds当我diffdayjs.

这是我的代码:

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

现在的问题是我得到了不同的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');

但这没有任何区别。

标签: javascript

解决方案


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

然后,您将拥有三个具有所需值的变量:totalHours totalMinutestotalSeconds


推荐阅读