js 根据指定日期获取前后一个月时间

188 阅读1分钟

需求:根据每月账单日获取近一月时间

举例:

账单日=每月15日

查询2023年2月的数据就是:“2023-01-15 到 2023-02-14”的数据

// 使用极端时间测试
const billingDate = '31'
// 先获取当前月和上月时间
const nowMonth = moment().endOf('months')
const lastMonth = moment().subtract(1, 'months').endOf('months')
// 判断当前月最后一天大于等于账单日则取账单日减1,否则取当前月最后一天
const nowBillingDate = nowMonth.date() >= billingDate ? billingDate - 1 : nowMonth.date()
// 判断上月最后一天大于账单日则取账单日减,否则取上月月最后一天
const lastBillingDate = lastMonth.date() > billingDate ? billingDate : lastMonth.date()
// 使用moment date方法设置日期并格式化
const startDate = lastMonth.date(lastBillingDate).startOf('days').format('YYYY-MM-DDTHH:mm:ss.SS')
const endDate = nowMonth.date(nowBillingDate).endOf('days').format('YYYY-MM-DDTHH:mm:ss.SS')
// 输出 ['2023-01-31T00:00:00.00', '2023-02-28T23:59:59.99']
this.dateRage = [startDate, endDate]