I got an ISO 8601 string as duration and I need to format it as XhYm( 1h20m). Does anyone have some suggestions?
What I did right now is this:
const duration = moment.duration(secondData.duration);
const formatted = moment.utc(duration.asMilliseconds()).format('HH:mm');
To get the output format you want, you'll need to set up the format string differently in the format()
call:
const duration = moment.duration('PT1H20M');
const formatted = moment.utc(duration.asMilliseconds()).format("H[h]m[m]");
Using the square brackets makes moment print those characters without trying to use them in the format. See the Escaping Characters in the momentjs documentation.
The simplest way to do it involves a little bit of manual formatting:
var d = moment.duration("PT1H20M");
console.log(d.hours()+"H"+d.minutes()+"M");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With