最近遇到一个对时间选择的范围限制,对传入的任意一个月份时间,限制只能选当月范围内的,查了一下资料大部分是限制当前月份的。主要的麻烦在于月的天数不同,需要处理,其余的就比较简单了,代码如下:
<el-date-picker :local="local" placeholder="请选择日期" :disabled-date="disabledDate" v-model="searchForm.time"
type="daterange" range-separator="至" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :default-value="new Date()">
</el-date-picker>
对时间的处理,我这里使用的是vue3框架,直接使用的setup语法糖
const searchForm = reactive({ time: "" });
const renyiTime = ref("2023-10");
// 大月
const DAMONTH = ["01", "03", "05", "07", "08", "10", "12"];
// 小月
const XIAOMONTH = ["04", "06", "09", "11"];
const disabledDate = function (time) {
const yearMonth = renyiTime.value.split("-");
const year = Number(yearMonth[0]);
const month = yearMonth[1];
let startTime = renyiTime.value + "-01 00:00:00"; // 拼接每月的第一天
let endTime = yearMonth[0] + "-" + yearMonth[1] + "-";
if (DAMONTH.includes(month)) {
endTime += "31 23:59:59"; //m每月的最后一天
} else if (XIAOMONTH.includes(month)) {
endTime += "30 23:59:59";
} else {
if (year % 4 === 0 && year % 400 === 0) {
endTime += "29 23:59:59"; // 2月份的特殊处理
} else {
endTime += "28 23:59:59";
}
}
return time.getTime() > new Date(endTime).getTime() || time.getTime() < new Date(startTime).getTime()
}