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?
You can use the
format()
function from moment.js.