1

i want to add months from user input to a particular date using javascript. tried every single method given for some duplicate questions but its still not worth it.

i am having a user subscription form in which i have a client created date .There is one input field where user enters the number of months subscribed. Now i want to create a label where i wanna print the subscription expiry date where i want to "add the client created date with the number of months subscribed"

Please help me for this problem.

Thank You in advance.

  • Where's your code? Given a JS date `someDate`, you can add months to it with `someDate.setMonth(someDate.getMonth() + numToAdd)`. – nnnnnn Sep 12 '16 at 05:47
  • You can declare the date object as `var nowDate = new Date(YYYY, MM, DD, HH, MM, SS)` , later you can add another Date object to it. Check out MDN's Date() documentation. – Prateek Gupta Sep 12 '16 at 05:49
  • If none of the existing solutions are helping you, please describe which ones you've tried and why they won't work in your case, otherwise we'll just give you the same answers again. From your question, it's not obvious why a simple setMonth shouldn't do. – David Hedlund Sep 12 '16 at 05:49
  • [If you use moment.js you can manipulate the object](http://momentjs.com/docs/#/manipulating/). – h2ooooooo Sep 12 '16 at 05:59

2 Answers2

1

You can use setMonth and geMonth. An example to add 4 months to today's date.

> var today = new Date();
> var numberOfMonths = 4
> today.setMonth(today.getMonth()+numberOfMonths);
SuperNova
  • 25,512
  • 7
  • 93
  • 64
0

dateTime manipulation is always a challenge for many programmers.

To avoid all the crazy calculations that can possibly give you headache and bugs - I would recommend you to have a look at the momentjs library.

You can easily add a month to the current date time using the .add() method.

Example:

console.log('1 month from current datetime is := ' + moment().add(1, 'months').format("MM-DD-YYYY"));
<script src="http://momentjs.com/downloads/moment.js"></script>

Here is the documentation for add API:
http://momentjs.com/docs/#/manipulating/

Samuel Toh
  • 18,006
  • 3
  • 24
  • 39