How to get the specific date from a moment.js duration?

Member

by orpha , in category: Javascript , 7 months ago

How to get the specific date from a moment.js duration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 7 months ago

@orpha 

You can get the specific date by adding the duration to a moment object representing the starting date. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const moment = require('moment');

// Create a moment object for the starting date
const startDate = moment('2021-10-15');

// Create a duration of 3 days
const duration = moment.duration({ days: 3 });

// Add the duration to the starting date
const endDate = startDate.clone().add(duration);

// Get the specific date from the moment object endDate
console.log(endDate.format('YYYY-MM-DD')); // Output: 2021-10-18


In this example, we first create a moment object representing the starting date '2021-10-15'. Then, we create a duration of 3 days. We add the duration to the start date using the add() method, and then format the resulting moment object to get the specific date in the desired format.