How do I use format() on a moment.js duration?


How do I use format() on a moment.js duration?

Is there any way I can use the moment.js format method on duration objects? I can’t find it anywhere in the docs and it doesn’t seen to be an attribute on duration objects.
I’d like to be able to do something like:
var diff = moment(end).unix() – moment(start).unix();

Also, if there are any other libraries which can easily accomodate this sort of functionality, I’d be interested in reccomendations.


Solution 1:

We are looking into adding some kind of formatting to durations in moment.js. See

A couple other libraries that might help out are and

Solution 2:

// set up
let start = moment("2018-05-16 12:00:00"); // some random moment in time (in ms)
let end = moment("2018-05-16 12:22:00"); // some random moment after start (in ms)
let diff = end.diff(start);

// execution
let f = moment.utc(diff).format("HH:mm:ss.SSS");

Have a look at the JSFiddle

Solution 3:

convert duration to ms and then to moment:


Solution 4:

Use this plugin Moment Duration Format.


moment.duration(123, "minutes").format("h:mm");

Solution 5:

var diff = moment(end).unix() - moment(start).unix();

Solution 6:

The best scenario for my particular use case was:

var duration = moment.duration("09:30"),
    formatted = moment.utc(duration.asMilliseconds()).format("HH:mm");

This improves upon @Wilson’s answer since it does not access private internal property _data.