Moment.js: Subtracting Time from a Date

To subtract time from a given date with moment.js, just follow the steps below:
1. Create a moment object with your date:
const date = moment('2022-15-09 13:30:45');
2. Construct a duration object from your time string with the moment.duration() method:
const duration = momment.duration('9:15:30');
3. Invoke the subtract() method on the moment object with the argument is the duration object created in the previous step:
const result = date.substract(duration);
Let’s examine a couple of examples below for more clarity.
Example 1
import moment from 'moment';
const dateOne = moment('2023-02-19 19:00:05');
const durationOne = moment.duration('13:30:45');
const resultOne = dateOne.subtract(durationOne);
console.log(resultOne.format('YYYY-MM-DD HH:mm:ss'));
Output:
2023-02-19 05:29:20
Example 2
import moment from 'moment';
const dateTwo = moment('2029-12-30 05:19:05');
const durationTwo = moment.duration({
year: 10,
month: 2,
day: 3,
hour: 4,
minute: 5,
second: 6,
});
const resultTwo = dateTwo.subtract(durationTwo);
console.log(resultTwo.format('YYYY-MM-DD HH:mm:ss'));
Output:
2019-10-27 01:13:59
That’s it. Further reading:
- 2 Ways to Format Currency in Javascript
- Javascript: Convert Relative URLs to Absolute URLs
- Node.js + Express + TypeScript: req.query type
- React: Create an Animated Side Navigation from Scratch
- Best Libraries for Formatting Date and Time in React
- Javascript: Capitalize the First Letter of Each Word (Title Case)
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
0 Comments