1.新建在utils文件夹中handleTime.js文件用于封装方法
javascript
// 计算当前周的开始和结束时间
export function calcNowWeek() {
let startWeek = moment().weekday(0).format('YYYY-MM-DD');
startWeek = moment(startWeek).subtract(2, 'days').format('YYYY-MM-DD')
let endWeek = moment().weekday(4).format('YYYY-MM-DD')
return { startWeek, endWeek }
}
// 计算当前月份的开始和结束时间
export function calcNowMonth() {
let startMonth = moment().startOf('month').format('YYYY-MM-DD');
let endMonth = moment().endOf('month').format('YYYY-MM-DD');
return { startMonth, endMonth }
}
// 计算当前季度的开始和结束时间
export function calcNowQuarter() {
let index = moment().quarter();
let year = moment().year();
let startQuarter = moment(`${year}-${3*(index-1) +1}-01`).format('YYYY-MM-DD');
let endQuarter = moment(`${year}-${3*index}-${new Date('2024',3*index,0).getDate()}`).format('YYYY-MM-DD');
return { startQuarter, endQuarter }
}
// 计算当前年的开始和结束时间
export function calcNowYear() {
let year = moment().year();
return {
startYear: `${year}-01-01`,
endYear: `${year}-12-31`
}
}
2.引入使用
javascript
import { calcNowWeek, calcNowMonth, calcNowQuarter, calcNowYear } from "@/utils/handleTime";
console.log(calcNowQuarter()) // 输出['2024-04-01','2024-06-30']