How to correctly add 1 month from the current and current date in moment.js

I read the documentation of the .js moment that if you want to add 1 month from the current date, you use this code

var moment = require('moment'); var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY'); 

But the problem is right now, it is incorrectly adding the date correctly, for example, let's say the current date is 10/31/2015, explain in the code

 var currentDate = moment().format('DD-MM-YYYY'); var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY'); console.log(currentDate) // Will result --> 31/10/2015 console.log(futureMonth) // Will result --> 30/11/2015 

if you look at the current calendar time, 1 month from 31/10/2015 supposedly 1/12/2015

Can someone give me some opinion on how to fix this problem.

thanks

+17
source share
2 answers
 var currentDate = moment('2015-10-30'); var futureMonth = moment(currentDate).add(1, 'M'); var futureMonthEnd = moment(futureMonth).endOf('month'); if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) { futureMonth = futureMonth.add(1, 'd'); } console.log(currentDate); console.log(futureMonth); 

Demo

EDIT

 moment.addRealMonth = function addRealMonth(d) { var fm = moment(d).add(1, 'M'); var fmEnd = moment(fm).endOf('month'); return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm; } var nextMonth = moment.addRealMonth(moment()); 

Demo

+38
source

According to the last document, you can do the following-

Add day

 moment().add(1, 'days').calendar(); 

Add year

 moment().add(1, 'years').calendar(); 

Add month

 moment().add(1, 'months').calendar(); 
0
source

All Articles