How to subtract time using moment.js?

by giovanny.lueilwitz , in category: Javascript , a year ago

How to subtract time using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , a year ago

@giovanny.lueilwitz 

To subtract time using moment.js, you can use the subtract method. Here's an example:

1
2
3
4
5
6
7
const moment = require('moment');

// Subtract 2 hours from the current time
const currentTime = moment();
const newTime = currentTime.subtract(2, 'hours');

console.log(newTime.format('HH:mm:ss')); // Output: the time 2 hours ago in HH:mm:ss format


In this example, currentTime.subtract(2, 'hours') subtracts 2 hours from the current time and returns a new moment object representing the updated time.

Related Threads:

How to subtract 1 month using moment.js?
How to find time difference in seconds using moment.js?
How to get time format to hh:mm using moment.js?
How to parse time string without offset using moment.js?
How to check if the time is in between given range using moment.js?
How to check if the current time is between two times using moment.js?