views:

572

answers:

3

I have a simple MVC form with the following elements:

<%= Html.TextBox("FechaInicio") %>

Which has the start date.

<%= Html.TextBox("Meses") %>

Which has the amount of months I want to add.

I'd like to take the date that has been entered on the first textbox, add the amount of months that have been entered on the second textbox and get that value.

A: 

I'd parse the value of the start date into a javascript date object. Then use something like below.

var startDate = parseDate();
var monthsToAdd = getMonthsToAdd();

while (startDate.getMonth() + monthsToAdd > 11) {
  startDate.setFullYear(startDate.getFullYear() + 1);
  monthsToAdd - 11;
}

startDate.setMonth(startDate.getMonth() + monthsToAdd);
Myles
That loop really isn't necessary. `Date` will handle month overflow for you automagically. See my answer.
Justin Johnson
gtk, the documentation didn't say that explicitly so I thought I would cover my bases.
Myles
+1  A: 

Using whatever date formation you've established, parse the value of FechaInicio into year, month and day. Get the value of Meses.

// Magical parsing of `FechaInicio` here
var year = 2010, month = 9, day = 14;
// The value of `meses`
var meses_mas = 3;

var future_date = new Date(year, month + meses_mas, day);

console.log(future_date);

You'll end up with Wed Apr 14 2011 00:00:00 GMT-0700 (PST) (timezone may vary). JavaScript's Date object will handle month overflow for you.

Also, as a side note, Date treats months as zero-indexed (0 = January ... 11 = December).

Justin Johnson
thanks for the info.
hminaya
Actually I just had to add a Number() to do a cast on each var before I added them..
hminaya
A: 

var numofMonthtoAdd = 5; //number of month you may want to add

        var beginDate = new Date();
        var month = (parseInt(beginDate.getMonth()) + parseInt(numofMonthtoAdd )) % 12;
        var year = (parseInt(beginDate.getMonth()) + parseInt(numofMonthtoAdd )) / 12;
        beginDate.setMonth(month);
        beginDate.setFullYear(parseInt(beginDate.getFullYear()) + year );
        return beginDate;
Allen Wang