Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 295
user8991667 Avatar asked Jan 09 '19 14:01

user8991667


2 Answers

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.

like image 77
Joseph Erickson Avatar answered Oct 26 '22 22:10

Joseph Erickson


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>
like image 39
ADyson Avatar answered Oct 26 '22 23:10

ADyson