1、【日期选择器】禁止选择今天之后的所有日期
<el-date-picker v-model="value1" type="date" placeholder="选择日期" :picker-options="pickerOptions0">
</el-date-picker>
data() {
return {
value1: '',
pickerOptions0: {
disabledDate(time) {
// 今天之后的日期都禁选,减去的8.64e7是今天,当前如果可以选择的话就不减
return time.getTime() > Date.now() - 8.64e7
}
}
}
},
分析:上面代码中 代码:time.getTime() > Date.now() - 8.64e7 是禁止选择包括今天之内的所有未来的日期
所以(注意区别,倒也不用刻意去记,写代码的时候试一下就可以了)
1、time.getTime() > Date.now() - 8.64e7 今天 + 未来的日期都不可以被选择
2、time.getTime() > Date.now() 未来的日期不可被选择
3、time.getTime() < Date.now() - 8.64e7 过去的日期不可被选择
4、time.getTime() < Date.now() - 8.64e7 今天 + 过去的日期不可被选择
2、【月份选择器】禁止选择本月之后的所有月份
<el-date-picker v-model="value1" type="month" placeholder="选择月" :picker-options="pickerOptions0">
</el-date-picker>
data() {
return {
value1: '',
pickerOptions0: {
// 本月之后的所有月份都是被禁选的
disabledDate: (time) => {
var date = new Date()
var year = date.getFullYear()
var month = date.getMonth() + 1
if (month >= 1 && month <= 9) {
month = '0' + month
}
var currentdate = year.toString() + month.toString()
var timeyear = time.getFullYear()
var timemonth = time.getMonth() + 2
if (timemonth >= 1 && timemonth <= 9) {
timemonth = '0' + timemonth
}
var timedate = timeyear.toString() + timemonth.toString()
return currentdate < timedate
}
}
}
},
分析:(在上面的代码中,var timemonth = time.getMonth() + 2 这里我加的是2,是因为我要禁选的月份包括本月)
1、当var timemonth = time.getMonth() + 2 ,currentdate < timedate,当前日期小于获取的日期的时候,
即:本月 + 未来的日期都不可以选择
2、 当var timemonth = time.getMonth() + 1,currentdate < timedate,当前日期小于获取的日期的时候,
即:未来的日期都不可以选择
3、当var timemonth = time.getMonth() ,currentdate > timedate,当前日期大于获取的日期的时候,
即:本月 + 过去的日期都不可以选择
4、当var timemonth = time.getMonth() + 1 ,currentdate > timedate,当前日期大于获取的日期的时候,
即:过去的日期都不可以选择
3、【月份选择器】过去的某一天~今天 仅此时间段可选
下面的例子是设置过去100天到今天的日期,除了这个时间段之外的其他的时间段都是不可以被选择的
<el-date-picker v-model="value1" type="date" placeholder="选择日期" :picker-options="pickerOptions0">
</el-date-picker>
data() {
return {
value1: '',
pickerOptions0: {
disabledDate(time) {
// 今天之后的日期都禁选
let curDate = (new Date()).getTime()
let three = 100 * 24 * 3600 * 1000
let threeMonths = curDate - three
return time.getTime() > Date.now() || time.getTime() < threeMonths
}
}
}
},
4、【月份选择器】今天~到未来某一天 仅此时间段可选
下面的例子是设置今天到未来50天的日期,除了这个时间段之外的其他的时间段都是不可以被选择的
<el-date-picker v-model="value1" type="date" placeholder="选择日期" :picker-options="pickerOptions0">
</el-date-picker>
data() {
return {
value1: '',
pickerOptions0: {
disabledDate(time) {
// 今天之后的日期都禁选
let curDate = (new Date()).getTime()
let three = 50 * 24 * 3600 * 1000
let threeMonths = curDate + three
return time.getTime() < Date.now() || time.getTime() > threeMonths
}
}
}
},
例子三和例四的原理和区别
选过去的时间段,那就是今天减去时间段的时间,你算出来的这个结点~到今天这个节点,这个时间段就是你要取的时间段
选未来的时间段,那就是今天加上时间段的时间,今天这个节点~你算出来的这个结点,这个时间段就是你要取的未来的时间段