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 February not exist.
If you want to add a month and, if the day is too great for the month, reduce the day to the last day of the month.
This is my fiddle code:
$(".demo").append("<p>Right</p>");
var dateSrt = new Date(2016, 7, 24);
for (var i = 1; i<=12; i++) {
if (i == 1) {
dateSrt.setMonth(dateSrt.getMonth());
} else {
dateSrt.setMonth(dateSrt.getMonth() + 1);
}
var txtDay = $.datepicker.formatDate('dd-mm-yy', dateSrt);
$(".demo").append("<label>" + txtDay + "</label><br>");
}
$(".demo").append("<p>Wrong (in this case if the date is incorrect must to be the last of the day)</p>");
var dateSrt=new Date(2016, 7, 30);
for (var i = 1; i<=12; i++) {
if (i == 1) {
dateSrt.setMonth(dateSrt.getMonth());
} else {
dateSrt.setMonth(dateSrt.getMonth() + 1);
}
var txtDay = $.datepicker.formatDate('dd-mm-yy', dateSrt);
$(".demo").append("<label>" + txtDay + "</label><br>");
}
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<div class="demo"></div>
Any suggestion?