我的使用场景 vue3后台项目
需求: 页面初始化时 显示当前年加月格式时间
首先封装 年+月时间公共方法util
//获取年份+月份格式 如'2023-08'
export const getYearMonth = (newDate) => {
// const currentDate = new Date()
const year = newDate.getFullYear()
const month = newDate.getMonth() + 1 // 月份从 0 到 11 表示,需要加 1
const yearAndMonth = year.toString() + '-' + month.toString().padStart(2, '0')
return yearAndMonth
}
此时拿到的yearAndMonth为String类型 如 '2023-08'
然后在当前页面 import 引入我们封装好的公共方法
获取当前时间
先定义
//获取当前年+月格式 如'2023-08'
const currentDate = new Date()
const yearMonth = getYearMonth(currentDate)
后取值
const queryParams = reactive({
// subsidyMonth: ['2023-08', '2023-08'],//补贴月份区间
subsidyMonth: [yearMonth, yearMonth], //补贴月份区间
})
这样就可以成功显示当前 年+月格式的时间了
效果如下