Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DayJS format seconds minutes and hours

Tags:

javascript

I want to format hours minutes seconds when I get the diff value from dayjs.

This is my code:

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

Now the problem is that I get difference like 0 hrs 3 min 228 sec.

How can I turn that into something like this: 00 hrs 03 min 59 sec?

I've tried to add this code after the push function:

    dayjs(newAppoint.occupied.hours).format('hh');
    dayjs(newAppoint.occupied.minutes).format('mm');
    dayjs(newAppoint.occupied.seconds).format('ss');

But it doesnt make any difference.

like image 554
zlotte Avatar asked Oct 16 '25 14:10

zlotte


1 Answers

The diff function returns the total number of seconds or minutes or hours rather than the component parts.

Try this:

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

you then have three variables with your needed values:totalHours totalMinutes and totalSeconds

like image 186
Nathaniel Johnson Avatar answered Oct 19 '25 15:10

Nathaniel Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!