业务上需要,根据账期来拆分日期
getMonthByPayment = (startDate, endDate) => {
const startArr = startDate.split('-')
let day = startArr[2]
const getLastDay = (year, month) => {
return year + '-' + (month < 10 ? '0' + month : month) + '-' + new Date(year, month, 0).getDate()
}
const getYearMonth = (date) => {
return date.getFullYear() + '-' + (date.getMonth() + 1 < 10 ? ('0' + (date.getMonth() + 1)) : date.getMonth() + 1)
}
let curr = new Date(startDate)
let end = new Date(endDate)
let arr = []
while (curr < end) {
let obj = {}
if (curr.getDate() <= Number(day)) {
obj.start = curr.format("yyyy-MM-dd")
let d = Number(curr.getMonth()) == 1 ? getLastDay(curr.getFullYear(), curr.getMonth() + 1).split('-')[2] : (Number(day) - 1)
if (curr.getDate() < Number(day) && new Date(getYearMonth(curr) + '-' + d) < end) {
obj.end = getYearMonth(curr) + '-' + d
} else {
let endThis = getLastDay(curr.getFullYear(), curr.getMonth() + 1)
if (new Date(endThis) < end) {
obj.end = endThis
} else {
obj.end = end.format("yyyy-MM-dd")
}
}
} else {
obj.start = getYearMonth(curr) + '-' + day
}
curr = new Date(new Date(obj.end).setDate(new Date(obj.end).getDate() + 1)) //在结束日期加一天
arr.push(obj)
}
return arr
}
format函数是挂在原型链上的格式化方法
执行 getMonthByPayment("2023-04-12","2023-08-20")
获得