$('.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 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? 解决方案 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 这篇关于jQuery添加月份至今的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-22 02:57