前言
实际开发中,有的时候产品要求需要用到日期筛选,日期筛选又需要用的当前日期的周日期范围,也有可能上一周,下一周这样的,相对应的也就又可能是当前日期的月日期范围,上一个月、下一个月的这样的:
那么,代码是如何实现的呢?
代码封装
- unil.js
/**
* 获取本周日期范围
*/
export const getCurrWeekDate = (num = 0) => {
// 创建一个新的 Date 对象
let d = new Date();
let date = d.getDate()
let week = d.getDay()
let firstDay = date - (week - 1) + num * 7
d.setDate(firstDay)
let year1 = d.getFullYear()
let m1 = d.getMonth() + 1
let month1 = m1 > 9 ? m1 : '0' + m1
let date1 = d.getDate() > 9 ? d.getDate() : '0' + d.getDate()
let firstDate = `${year1}年${month1}月${date1}日`
let lastDay = date + (7 - week) + num * 7
let d2 = new Date()
d2.setDate(lastDay)
let year2 = d2.getFullYear()
let m2 = d2.getMonth() + 1
let month2 = m2 > 9 ? m2 : '0' + m2
let date2 = d2.getDate() > 9 ? d2.getDate() : '0' + d2.getDate()
let lastDate = `${year2}年${month2}月${date2}日`
return `${firstDate}~${lastDate}`
}
/**
* 获取本月日期范围
*/
export const getCurrMonthDate = (num = 0) => {
// 创建一个新的 Date 对象
let date = new Date();
let month = date.getMonth() + 1 + num
date.setMonth(month - 1)
let year = date.getFullYear()
let mm = date.getMonth() + 1
let m = mm > 9 ? mm : '0' + mm
// 设置为每月第一天
date.setMonth(0); // 注意这里的参数是从0开始计算的,所以要将月份-1
// 获取本月最后一天的日期
let lastDay = new Date(year, m, 0)
.getDate();
let lastDayOfMonth = lastDay > 9 ? lastDay : '0' + lastDay
return `${year}年${m}月01日~${year}年${m}月${lastDayOfMonth}日`
}
方法中的参数
num
代表的是上一周还是上两周或者是下一周、下两周。往上就是传负数,往下就是传正数;如上一周,传-1,下一周,传1,以此类推。
调用示例
这里直接基于ui设计以及代码复用将方法写一个通用方法调用:
以下调用环境是在vue2的环境中调用示例的,其他环境注意切换写法。
// 封装一个复用方法
getCurrDateText(type, num = 0) {
let d = new Date()
switch (type) {
case '1': // 日
let newDate = d.getDate() + num
d.setDate(newDate)
let M = d.getMonth() + 1
let mm = M > 9 ? M : '0' + M
let year = d.getFullYear()
let dd = d.getDate() > 9 ? d.getDate() : '0' + d.getDate()
this.currDate = `${year}年${mm}月${dd}日`
break
case '2': // 周
this.currDate = getCurrWeekDate(num)
break
case '3': // 月
this.currDate = getCurrMonthDate(num)
break
case '4': // 季度
let month = d.getMonth() + 1
let m = month + num * 3
d.setMonth(m)
let newMonth = d.getMonth()
let y = d.getFullYear()
if (newMonth <= 3) {
this.currDate = `${y}年01月~${y}年03月`
} else if (newMonth <= 6) {
this.currDate = `${y}年04月~${y}年06月`
} else if (newMonth <= 9) {
this.currDate = `${y}年07月~${y}年09月`
} else {
this.currDate = `${y}年10月~${y}年12月`
}
break
default:
break
}
},
- 点击上一天/上一周/上一个月/上一季度
// this.currTab 初始值为0
getLastDates() {
let type = (this.currTab + 1).toString()
this.dateNum--
this.getCurrDateText(type, this.dateNum)
// reload data...
}
- 点击下一天/下一周/下一个月/下一季度
getNextDates() {
let type = (this.currTab + 1).toString()
this.dateNum++
this.getCurrDateText(type, this.dateNum)
// reload data...
}