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

Member

by orpha , in category: Javascript , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , a year 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.

Related Threads:

How to check if today and specific date is same using moment.js?
How to get a date with a specific time in JavaScript?
How to get the duration of a video in iframe?
How to get date string from day number and month number using moment.js?
How to get the duration with postgresql?
How to parse date string with '0' day to date in moment.js?