user8991667
user8991667

Reputation: 95

Moment js format duration

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');

Upvotes: 4

Views: 14438

Answers (2)

ADyson
ADyson

Reputation: 61849

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>

Upvotes: 2

Joseph Erickson
Joseph Erickson

Reputation: 2294

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.

Upvotes: 14

Related Questions