1. 使用场景
elemet-plus 组件库,日期选择器快捷使用选择本月,本季度时间…
2. 方法
const useDate = () => {const now = new Date() // 当前日期const nowYear = now.getFullYear() //当前年const nowMonth = now.getMonth() //当前月const nowDay = now.getDate() // 当前日const nowDayOfWeek = now.getDay() // 周几const jd = Math.ceil((nowMonth + 1) / 3) // 当前季度// 当天function getCurDay() {return [now, now]}// 本周function getCurWeek() {const startDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek)const endDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek))return [startDate, endDate]}// 本月function getCurMonth() {const startDate = new Date(nowYear, nowMonth, 1)const endDate = new Date(nowYear, nowMonth + 1, 0)return [startDate, endDate]}// 本季度function getCurQuarter() {const startDate = new Date(nowYear, (jd - 1) * 3, 1)const endDate = new Date(nowYear, jd * 3, 0)return [startDate, endDate]}// 本半年function getCurHalfYear() {const startD = new Date(nowYear, nowMonth - 4, 1)const startDate = new Date(nowYear, 0, 1)const endD = new Date(nowYear, nowMonth + 1, 0)const year = startD.getFullYear()if (year === nowYear) {return [startD, endD]} else {return [startDate, endD]}}// 本年function getCurYear() {const startDate = new Date(nowYear, 0, 1)const endDate = new Date(nowYear, 11, 0)return [startDate, endDate]}return {getCurDay,getCurWeek,getCurMonth,getCurQuarter,getCurHalfYear,getCurYear,}}const {getCurDay,getCurWeek,getCurMonth,getCurQuarter,getCurHalfYear,getCurYear,} = useDate()export const shortcuts = [{text: '当天',value: getCurDay(),},{text: '本周',value: getCurWeek(),},{text: '本月',value: getCurMonth(),},{text: '本季度',value: getCurQuarter(),},{text: '半年',value: getCurHalfYear(),},{text: '当年',value: getCurYear(),},]
如有疑问欢迎留言交流,有更好的方法希望不吝赐教~