How to subtract time using moment.js?

by giovanny.lueilwitz , in category: Javascript , 7 months ago

How to subtract time using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 6 months 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.