Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Momentjs add doesn't work

Tags:

momentjs

 var startDate = moment("2017-06-30 00:00 +0000", "YYYY-MM-DD HH:mm Z");
 var endDate = startDate.clone();
 endDate.add(2, 'days');
 console.log('startDate', startDate);
 console.log('endDate', endDate);

I'm trying to add 2 days to the startdate but the endDate remains the same as the startdate. Am I doing something wrong?

like image 452
Vincent Avatar asked Jun 30 '17 08:06

Vincent


People also ask

Is Momentjs deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

Should you still use Momentjs?

Moment. js is a fantastic time & date library with lots of great features and utilities. However, if you are working on a performance sensitive web application, it might cause a huge performance overhead because of its complex APIs and large bundle size.

What can I use instead of Momentjs?

There are several libraries out there that can potentially replace Moment in your app. The creators of Moment recommend looking into Luxon, Day. js, date-fns, js-Joda, or even replacing Moment with native JS.


1 Answers

To add days you can simpley use moment().add(2) here 2 is the number of days you wish to add

 var startDate = moment("2017-06-30 00:00 +0000", "YYYY-MM-DD HH:mm Z");
 var endDate = startDate.clone();
 endDate.add(2); // or use endDate.add(2, 'day')
 console.log('startDate', startDate);
 console.log('endDate', endDate);
<script src="https://momentjs.com/downloads/moment.js"></script>

If you like to add months or year just give the second parameter as months or years

 var startDate = moment(); // assign today
 console.log('After 2 days:', startDate.add(2, 'days')); // startDate.add(2, 'day') 
 console.log('After 2 months:', moment().add(2, 'months')); // or startDate.add(2, 'month') 
 console.log('After 2 years:', moment().add(2, 'years')); // or startDate.add(2, 'year') 
<script src="https://momentjs.com/downloads/moment.js"></script>
like image 59
Deepu Reghunath Avatar answered Nov 07 '22 12:11

Deepu Reghunath