获取上个月,支持跨年

一、获取上个月,支持跨年

// 获取上个月

import { moment } from '@/filters/moment'

const now = new Date()

const prevMonth = moment(now.setMonth(now.getMonth() - 1), 'YYYY-MM')

// 如果当前月是2022-04,则输出2022-03,如果当前月是2022-01,则输出2021-12,以此类推
console.log(prevMonth)

二、获取上几个月,同样支持跨年

只要把 now.setMonth(now.getMonth() - 1) 的1换成你想要的即可。例如:

// 获取上几个月

import { moment } from '@/filters/moment'

const now = new Date()

let month= moment(now.setMonth(now.getMonth() - 3), 'YYYY-MM')

// 如果当前月是2022-04,则输出2022-01,如果当前月是2022-02,则输出2021-11,以此类推
console.log(month)

三、注意点

当需要多次调用语句 now.setMonth(now.getMonth() - 1) 时,要注意执行该语句是会直接改变now值的。

看下面的例子:

import { moment } from '@/filters/moment'

const now = new Date() // 假设当前月是2022-04

let month= moment(now.setMonth(now.getMonth() - 1), 'YYYY-MM')

console.log(month) // 输出2022-03

month= moment(now.setMonth(now.getMonth() - 1), 'YYYY-MM')

console.log(month) // 输出2022-02

month= moment(now.setMonth(now.getMonth() - 2), 'YYYY-MM')

console.log(month) // 输出2021-12

全文完。记录于2022-04-07

猜你喜欢

转载自blog.csdn.net/qq_40146789/article/details/123985987