How to properly add 1 month from now to current date in moment.js

Javascriptnode.jsDateMomentjs

Javascript Problem Overview


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

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

But the problem right now, it is not properly add the date correctly, for example let say the current date is 31/10/2015, explain in 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 take a look at the current calendar time, 1 month from 31/10/2015 supposed to be 1/12/2015

Could anyone give me some opinion on how to fix this problem.

Thank you

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

> According to the latest doc you can do the following-

Add a day

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

Add Year

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

Add Month

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

Solution 3 - Javascript

startDate = "20.03.2020";
var newDate = moment(startDate, "DD-MM-YYYY").add(5, 'days');
console.log(newDate)

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Solution 4 - Javascript

You could try

moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJack MoscoviView Question on Stackoverflow
Solution 1 - JavascriptsilentwView Answer on Stackoverflow
Solution 2 - JavascriptAnoop M MaddasseriView Answer on Stackoverflow
Solution 3 - JavascriptNishithView Answer on Stackoverflow
Solution 4 - JavascriptAnusha NilapuView Answer on Stackoverflow