Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!