The example in this article describes the method of adding days to a given time in JavaScript. Share it with everyone for your reference, the details are as follows:
/** * 时间相加处理函数 * @param date 需要计算的时间(xxxx-xx-xx) * @param plusDays 要加的天数(整数) */ function calcuDate(date, plusDays) { var dateArray = date.split("-"); var year = +dateArray[0]; var month = +dateArray[1]; var day = +dateArray[2]; var oriDay = day; var secondMonthDays = ((year%4 === 0 && year%100 !== 0) || year%400 === 0) ? 29 : 28; while(plusDays>0) { oriDay = day day += plusDays; switch(month) { case 4: case 6: case 9: case 11: if(day > 30) { plusDays -= (30-oriDay)+1; month++; day = 1; } else { plusDays = 0; } break; case 2: if(day > secondMonthDays) { plusDays -= (secondMonthDays-oriDay)+1; month++; day = 1; } else { plusDays = 0; } break; default: if(day > 31) { plusDays -= (31-oriDay)+1; day = 1; month++; } else { plusDays = 0; } } if(month>12) { month = 1; year++; } } return createTimeString(year, month, day); }
Of course, in addition to this method, there are other solutions, such as passing parameters with new Date. This can be considered one of them
Readers who are interested in more content related to JavaScript time and date operations can check out this site's special topic: "Summary of JavaScript time and date operation skills"
I hope this article will be helpful to everyone in JavaScript programming.