Moment.js: Subtract 2 Dates and Format the Result

Last updated on September 15, 2022 Snowball Loading... Post a comment

In order to subtract 2 dates with Moment.js, you can follow the steps below:

1. Construct moment date objects from your date strings:

const dateOne = moment('2020-12-30 12:00:00');
const dateTwo = moment('2023-12-31 19:30:45');

3. Let’s say dateTwo is the minuend and dateOne is the subtrahend. We’ll invoke the diff() method on the object dateTwo with the passed in argument is dateOne:

const duration = dateTwo.diff(dateOne);

3. By default, the result is milliseconds and it is truncated to zero decimal places. If you want the result in the HH:mm:ss format, then you can do the following:

const duration = dateTwo.diff(dateOne);
const formattedDuration = moment.utc(duration).format('HH:mm:ss');

You can also directly specify the result as years, months, weeks, days, hours, minutes by passing the corresponding word as the second argument. In case you want a floating point number, pass true as the third argument.

const duration = dateTwo.diff(dateOne, 'hours', true);

Complete example:

import moment from 'moment';

const dateOne = moment('2020-12-30 12:00:00');
const dateTwo = moment('2023-12-31 19:30:45');
const duration = dateTwo.diff(dateOne);

const formattedDuration = moment.utc(duration).format('HH:mm:ss');

console.log(formattedDuration);

Output:

07:30:45

That’s it. Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like