拆分日期的方法

业务上需要,根据账期来拆分日期

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")

获得

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值