开发者

Add months to a date using jQuery

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.


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).


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);


        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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜