Tip of the Day: Calculating durations with Moment

Moment has quite a nice fluent interface for some operations, others just need a little more thought.

For example, I wanted the duration of something and I had recorded the start and end time. I thought something like this, finding the difference between two dates and converting it to a duration, would work:

var duration = endTime.diff(startTime).duration().asSeconds();

However, that doesn’t work.

What you have to do is find the difference, then pass that into the duration function, like this:

var duration = moment.duration(endTime.diff(startTime)).asSeconds();

And now I get what I wanted.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s