// 获取当前日期
let currentDate = new Date();
// 获取当前月份和年份
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
// 月份加一
let nextMonthDate = new Date(currentYear, currentMonth + 1, currentDate.getDate());
// 如果加一个月后天数不一致(例如从31号跳到下个月),则调整为最后一天
if (nextMonthDate.getDate() !== currentDate.getDate()) {
nextMonthDate = new Date(currentYear, currentMonth + 1, 0); // 设置为上个月的最后一天
}
console.log("当前日期: ", currentDate);
console.log("加一个月后的日期: ", nextMonthDate);
new Date() 获取当前日期。getMonth() 和 getFullYear() 获取当前的月份和年份。Date 对象,将月份加一。注意月份是从0开始计数的(0表示1月,11表示12月)。希望这段代码能帮助你理解如何在 JavaScript 中给日期加一个月。
上一篇:js 时间差
下一篇:js 日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站