Skip to content Skip to sidebar Skip to footer

Jquery Add Month To Date

I need to add a month to a date in jQuery. It's all ok, but when the date is 29 or 30 or 31 I have a problem because 31 November not exist, 30 February not exist and sometimes 29 F

Solution 1:

Seems like you can simply check that the new month number is more than current month number + 1, then set the previous month's last day:

$('.demo').append('<p>Right</p>');
var dateSrt = new Date(2016, 6, 30);
var currentDay = dateSrt.getDate();

for (var i = 0; i <= 11 ; i++) {
    var currentMonth = dateSrt.getMonth();
    dateSrt.setMonth(currentMonth + 1, currentDay);

    if (dateSrt.getMonth() > currentMonth + 1) {
        dateSrt.setDate(0);
    }

    var txtDay = $.datepicker.formatDate('dd-mm-yy', dateSrt);
    $('.demo').append('<label>' + txtDay + '</label><br>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="demo"></div>

JSFiddle


Solution 2:

This approach requires the use of datejs (datejs.com) We can add a month to a date very easily as:

var jan312009 = new Date(2009, 1-1, 31);
var oneMonthFromJan312009 = new Date(jan312009).add(1).month();

The output of the above will be like this;

Sat Jan 31 2009 00:00:00 GMT+1100 (EST)
Sat Feb 28 2009 00:00:00 GMT+1100 (EST)

For more info you can find it here:

http://www.markhneedham.com/blog/2009/01/07/javascript-add-a-month-to-a-date/

Thanks

Also here is working fiddle link that uses dates.js to add number of months in the current date. You can modify it accordingly.

http://jsfiddle.net/J3cPD/

Thanks


Post a Comment for "Jquery Add Month To Date"