0

I want to calculate a new date by adding a number of months to a specific date.

For example:

I have a date "06/30/2012" (30th June 2012), and a number of months "2" or "3" months.

Now I want a function which gets both values and returns a date which is 2 months after the specified date.

Please show me how this can be achieved.

Ghoul Fool
  • 6,249
  • 10
  • 67
  • 125
Aditya P Bhatt
  • 21,431
  • 18
  • 85
  • 104
  • Some one answer it here already, you should search first http://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript – James Jun 29 '12 at 06:52
  • Possible duplicate http://stackoverflow.com/questions/5645058/how-to-add-months-in-javascript-date – bart s Jun 29 '12 at 06:54

3 Answers3

1

You can try putting this code, Which has everything you need with date Addition/Subtraction

Date.prototype.add = function (sInterval, iNum){
      var dTemp = this;
      if (!sInterval || iNum == 0) return dTemp;
      switch (sInterval.toLowerCase()){
        case "ms":
          dTemp.setMilliseconds(dTemp.getMilliseconds() + iNum);
          break;
        case "s":
          dTemp.setSeconds(dTemp.getSeconds() + iNum);
          break;
        case "mi":
          dTemp.setMinutes(dTemp.getMinutes() + iNum);
          break;
        case "h":
          dTemp.setHours(dTemp.getHours() + iNum);
          break;
        case "d":
          dTemp.setDate(dTemp.getDate() + iNum);
          break;
        case "mo":
          dTemp.setMonth(dTemp.getMonth() + iNum);
          break;
        case "y":
          dTemp.setFullYear(dTemp.getFullYear() + iNum);
          break;
      }
      return dTemp;
    }

    //sample usage
    var d = new Date();
    var d2 = d.add("d", 3); //+3days
    var d3 = d.add("h", -3); //-3hours
    var d4 = d.add("mo", 2); //+2 Months
RPB
  • 16,006
  • 16
  • 55
  • 79
0

Parse out the pieces and reconstruct:

function addMonths(d, offset)
{
    return new Date(d.getFullYear(), d.getMonth()+offset, d.getDate());
}

var d = new Date();
console.log(d.toDateString());
// Thu Jun 28 2012

var twoMonthsFromNow = addMonths(d, 2);
console.log(twoMonthsFromNow.toDateString());
// Sun Aug 28 112
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
0

If you want to go into next month when days overflow, then

var d = new Date(2012, 6-1, 30);
d.setMonth(d.getMonth()+3);

if you want to stay within the new month,adjusting your date, then

var d = new Date(2012, 6-1, 30);
var add_months = 8
var d2 = new Date(Math.min(new Date(d.getYear(), d.getMonth()+add_months+1, 0),
              new Date(d.getYear(), d.getMonth()+add_months, d.getDate())))
panda-34
  • 4,089
  • 20
  • 25