4

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.

frenchbaguette
  • 1,297
  • 6
  • 22
  • 41
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart – John Krakov Sep 18 '19 at 21:14
  • See this similar question for a solution. https://stackoverflow.com/questions/18889548/javascript-change-gethours-to-2-digit – Roskow Sep 18 '19 at 21:16
  • 3
    I think you are trying to get hours, min and seconds from dayjs. If so, you are wrong, because it will return the diff in the provided unit, like min or seconds. I think what you need is to just get the seconds by `seconds: dayjs().diff(user.appointment, 'second')` and format the seconds in the desired `hh mm ss` string by using `padStart` – iamkhush Sep 18 '19 at 21:19
  • @iamkhush Yeah. I've also tried to convert seconds only and it worked. Thanks :) – frenchbaguette Sep 18 '19 at 21:55

1 Answers1

8

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

Nathaniel Johnson
  • 4,731
  • 1
  • 42
  • 69