日期选择器el-date-picker选择周、月、年

 
          
          
{{ weekRange }}
{{ timeRange }}
export default { data(){ return{ date: '', startDate: '', endDate: '', } } method:{ // 周选择器 handleWeekChange(value) { if (value) { console.log(value) // 获取周的第一天(周一) const weekStart = new Date(value) const dayOfWeek = weekStart.getDay() // 周日是0,周一是1,... // 如果周的第一天不是周一,则回退到上一周的周一 if (dayOfWeek !== 1) { weekStart.setDate(weekStart.getDate() - dayOfWeek + 1) } // 计算周的最后一天(周日) const weekEnd = new Date(weekStart) weekEnd.setDate(weekEnd.getDate() + 6) // 存储周的开始和结束日期 this.startDate = weekStart this.endDate = weekEnd this.sonData.startDate = this.formatDate(this.startDate) this.sonData.endDate = this.formatDate(this.endDate) // console.log('this.endDate',this.formatDate(this.endDate)) } }, // 月选择器获取月份日期范围 handleMonthChange(value) { // 确保value是一个有效的Date对象 if (value) { // 获取月份的第一天 const firstDay = new Date(value.getFullYear(), value.getMonth(), 1) // 获取下一个月的第一天 const nextMonthFirstDay = new Date(value.getFullYear(), value.getMonth() + 1, 1) // 获取当前月份的最后一天(即下一个月第一天的前一天) const lastDay = new Date(nextMonthFirstDay - 86400000) // 一天有86400000毫秒 // 更新组件数据 this.startDate = this.formatDate(firstDay) this.endDate = this.formatDate(lastDay) this.timeRange = this.startDate + ' 至 ' + this.endDate this.sonData.startDate = this.startDate this.sonData.endDate = this.endDate } }, // 年选择器 getYearRange(value) { // 确保value是一个有效的Date对象 if (value) { this.startDate = '' this.endDate = '' // 获取年份的第一天(1月1日) const firstDay = new Date(value.getFullYear(), 0, 1) // 月份从0开始,0代表1月 // 获取年份的最后一天(12月31日) const lastDay = new Date(value.getFullYear(), 11, 31, 23, 59, 59, 999) // 月份从0开始,11代表12月 // 更新组件数据 this.startDate = this.formatDate(firstDay) this.endDate = this.formatDate(lastDay) this.timeRange = this.startDate + ' 至 ' + this.endDate this.sonData.startDate = this.startDate this.sonData.endDate = this.endDate } }, // 辅助函数:格式化日期为 "YYYY-MM-DD" formatDate(date) { const year = date.getFullYear() const month = (date.getMonth() + 1).toString().padStart(2, '0') // 填充前导零 const day = date.getDate().toString().padStart(2, '0') // 填充前导零 return `${year}-${month}-${day}` }, } }

你可能感兴趣的:(javascript,前端,开发语言)