Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Formatting Duration in Correct Format `HH:MM`

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading