Formatting Duration in Correct Format `HH:MM`

125 views Asked by At

I have some logic designed to generate a formatted duration based on an inputted start and stop time:

  getFormattedDuration = async (stopValue, startValue) => {
    const durValue = moment(stopValue, "H:mm").diff(moment(startValue, "H:mm"));
    const t = moment.duration(durValue);

    const duration = {
      hours: t.hours(),
      minutes: t.minutes()
    }

    const formattedDuration = `0${duration.hours}:${duration.minutes}`;
    return formattedDuration;

    // I'm prepending a `0` here because I know the duration will never be above a certain limit - i.e. it will never get to a double digit number for hours.

  } 

This works for the most part. But on occasion I will end up with something like this for output:

duration:  Object {
  "hours": 0,
  "minutes": 8,
}

formattedDuration:  00:8

What I want here is 00:08. How can I pad with zeroes, as necessary, to ensure I get a correctly formatted duration value - which should be in this format hh:mm. Does moment.js have a function I can use to handle this?

2

There are 2 answers

0
Maik Lowrey On BEST ANSWER

You can use the format() function from moment.js.

const m = moment('00:8','HH:mm').format('HH:mm');

console.log(m) // "00:08"

m = moment('00:8','HH:mm').format('HH:mm');

console.log(m)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

0
Felix G On

You could use to .padStart() to ensure there are leading zeros.