How to 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();
moment.duration(diff).format('hh:mm:ss')

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

Thanks!

31 Answers
31

// 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");
alert(f);

Have a look at the JSFiddle

Leave a Comment