function getLastMonth(date) {
const now = new Date(date)
const year = now.getFullYear();
const month = now.getMonth() + 1; // 0-11表示1-12月
const day = now.getDate();
const nowMonthDay = new Date(year, month, 0).getDate(); // 当前月的总天数
let res = null
if (month - 1 <= 0) {
// 如果是1月,年数往前推一年
res = year - 1 + "-" + 12 + "-" + day;
} else {
const lastMonthDay = new Date(year, parseInt(month) - 1, 0).getDate();
if (lastMonthDay < day) {
// 1个月前所在月的总天数小于现在的天日期
if (day < nowMonthDay) {
// 当前天日期小于当前月总天数
res = year + "-" + (month - 1) + "-" + (lastMonthDay - (nowMonthDay - day));
} else {
res = year + "-" + (month - 1) + "-" + lastMonthDay;
}
} else {
res = year + "-" + (month -1) + "-" + day;
}
}
return res;
}
去除else后:
function getLastMonth(date) {
const now = new Date(date)
const year = now.getFullYear();
const month = now.getMonth() + 1;
const day = now.getDate();
const nowMonthDay = new Date(year, month, 0).getDate(); // 当前月的总天数
if (month - 1 <= 0) return year - 1 + "-" + 12 + "-" + day; // 如果是1月,年数往前推一年
const lastMonthDay = new Date(year, parseInt(month) - 1, 0).getDate();
if (lastMonthDay >= day) return year + "-" + (month -1) + "-" + day;
if (day < nowMonthDay) return year + "-" + (month - 1) + "-" + (lastMonthDay - (nowMonthDay - day)); // 1个月前所在月的总天数小于现在的天日期
return year + "-" + (month - 1) + "-" + lastMonthDay; // 当前天日期小于当前月总天数
}