How to get future date in moment.js?

Member

by loy , in category: JavaScript , 2 years ago

How to get future date in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by kelly , 2 years ago

@loy Use add() method in moment.js to get future dates, code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import moment from "moment";

let tomorrow = new moment().add(1, 'day');
let now = new moment();

// Output: 2022-07-05T11:51:44-07:00 
console.log(now.format())

// Output: 2022-07-06T11:51:44-07:00 
console.log(tomorrow.format());

let futureHours = new moment().add(6, 'hour');

// Output: 2022-07-05T17:51:44-07:00 
console.log(futureHours.format());

Member

by kendrick , 10 months ago

@loy 

You can use the .add() method in Moment.js to get a future date. Here's an example:

1
2
3
4
const today = moment();
const futureDate = today.add(1, 'week'); // add 1 week to today's date

console.log(futureDate.format('YYYY/MM/DD')); // prints the future date in YYYY/MM/DD format


In the example above, we're getting the current date using moment(). Then, we're using add() to add 1 week to today's date. Finally, we're formatting the future date using .format() and printing it to the console. You can change the duration and units passed as the arguments to add() depending on how far in the future you want the date to be.