限制开始时间和结束时间
// 接口返回的时间格式为 startTime: "2021-07-28 17:05" endTime: "2021-07-30 09:00"
<el-row :gutter="20">
<el-col :span="20" class="blk-double-time">
<el-form-item label="项目时间" prop="startTime" :rules="[rules.required]">
<el-date-picker
v-model="Form.startTime"
type="datetime"
value-format="yyyy-MM-dd HH:mm"
format="yyyy-MM-dd HH:mm"
:picker-options="startDatePicker"
:readonly="isEnable===true"
@change="handleStartDate"
/>
</el-form-item>
<span>~</span>
<el-form-item label="" prop="endTime" :rules="[rules.required]">
<el-date-picker
v-model="Form.endTime"
type="datetime"
value-format="yyyy-MM-dd HH:mm"
format="yyyy-MM-dd HH:mm"
:picker-options="endDatePicker"
@change="handleEndDate"
/>
</el-form-item>
</el-col>
</el-row>
// data中
startDatePicker: this.startDate(),
endDatePicker: this.endDate(),
// methods中
// 限制开始时间和结束时间,开始时间不能高于结束时间,结束时间不可低于开始时间
startDate() {
return {
disabledDate: (time) => {
if (this.Form.endTime && this.Form.endTime.length > 0) {
if (time.getTime() > new Date(this.Form.endTime).getTime()) {
return true;
}
if (time.getTime() < Date.now() - 8.64e7) {
return true;
}
} else {
if (time.getTime() < Date.now() - 8.64e7) {
return true;
}
}
}
};
},
endDate() {
return {
disabledDate: (time) => {
const startTime =
this.Form.startTime &&
this.Form.startTime.length > 0
? new Date(this.Form.startTime).getTime() - 8.64e7
: Date.now();
return time.getTime() < startTime;
}
};
},
// 若选择的时间小于等于现在的时间,点击此刻或确定默认开始时间大于当前时间一分钟,只对格式为yyyy-MM-dd HH:mm有用,若加上秒,修改time.js即可
handleStartDate() {
var startAt = new Date(this.Form.startTime) * 1000 / 1000;
if (startAt <= Date.now()) {
const nowTime = new Date();
nowTime.setMinutes(nowTime.getMinutes() + 1);
this.Form.startTime = timeFormat(nowTime);
}
},
handleEndDate() {
var startAt = new Date(this.Form.startTime) * 1000 / 1000;
var endAt = new Date(this.Form.endTime) * 1000 / 1000;
// var time = new Date();
// time.setHours(23, 0, 0);
if (endAt <= startAt) {
var start = new Date(startAt); //
start.setMinutes(start.getMinutes() + 1); //
this.Form.endTime = timeFormat(start);
}
},
// utils中的time.js
export function timeFormat(nowTime) {
const y = nowTime.getFullYear();
let m = nowTime.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
let d = nowTime.getDate();
d = d < 10 ? ('0' + d) : d;
let h = nowTime.getHours();
h = h < 10 ? ('0' + h) : h;
let M = nowTime.getMinutes();
M = M < 10 ? ('0' + M) : M;
const time = y + '-' + m + '-' + d + ' ' + h + ':' + M;
return time;
}