Moment.js: Subtract 2 Dates and Format the Result

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:
- Moment.js: Subtracting Time from a Date
- Node.js + Express + TypeScript: req.query type
- 2 Ways to Format Currency in Javascript
- CSS & Javascript: Change Background Color on Scroll
- Javascript: How to Reverse an Integer
- Javascript Object: Find the Key(s) of a given Value
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.