El rango de tiempo limitado del selector de fecha y hora DateTimePicker tiene una precisión de horas, minutos y segundos

Requisitos: la hora de inicio y la hora de finalización son dos elementos, la hora de inicio es mayor que la hora actual, la hora de finalización es mayor que la hora de inicio, exacta a la hora.

inserte la descripción de la imagen aquí

código HTML:

<el-date-picker
 	v-model="bgnDate"
     type="datetime"
     placeholder="开始日期"
     :picker-options="pickerOptions0"
     @change="changetime">
 </el-date-picker><el-date-picker
     v-model="endDate"
     type="datetime"
     placeholder="结束日期"
     :picker-options="pickerOptions1"
     :default-time="defaultTime"
     @change="endTimeChange"
     >
 </el-date-picker>

La hora límite de inicio es mayor que la hora actual (pero el día actual es opcional)

data(){
    
    
	return{
    
    
	bgnDate:'',
	endDate:'',
	pickerOptions0: {
    
    
        disabledDate: (time) => {
    
    
            return time.getTime() < Date.now() - 8.64e7;
          }
      },
  }
}

Limite el tiempo de finalización

computed:{
    
    
	 //默认结束时间
    defaultTime(){
    
    
      if(!this.bgnDate){
    
    
        return
      }
      let hours = this.bgnDate.getHours();//时
      let min = this.bgnDate.getMinutes();//分
      let second = this.bgnDate.getSeconds();//秒
      //默认比开始时间多一秒
      return hours+':'+min+':'+(second+1) 
    },
    
    //结束时间限制规则
    pickerOptions1(){
    
    
      if(!this.bgnDate){
    
    
        return 
      }
      //前推一天,防止当天日期无法选择
      let hours = this.bgnDate.getHours();//时
      let min = this.bgnDate.getMinutes();//分
      let second = this.bgnDate.getSeconds();//秒
      //如果开始时间是0点的话则不用再减一天,如果不是0点则减一天,防止结束时间不能选开始时间这一天
      let preTime =hours == '00'&&min == '00'&&second == '00'?
		      new Date(this.bgnDate).getTime() : 
		      new Date(this.bgnDate).getTime() - 8.64e7;
      
      let str = ""
      let k = false

      if(this.endDate){
    
    
      //判断结束时间和开始时间是否是同一天
        k = (this.bgnDate.getFullYear() ==this.endDate.getFullYear()) &&
          (this.bgnDate.getMonth() ==this.endDate.getMonth()) &&
          (this.bgnDate.getDate() ==this.endDate.getDate())
      }
      //如果是同一天,则秒数+1
      if(k){
    
    
        let hours = this.bgnDate.getHours();//时
        let min = this.bgnDate.getMinutes();//分
        let second = this.bgnDate.getSeconds();//秒
        str=hours+':'+min+':'+ (second+1)
      }else{
    
    
        str = "00:00:00"
      }

      return {
    
    
      //控制日期不可选开始时间之前
        disabledDate: (time) => {
    
    
          return time.getTime() < preTime ;
        },
        //控制时间只能选以上代码限制的部分
        selectableRange: str + " - 23:59:59"
      }
    },

}

En este punto, no hay ningún problema en teoría, pero hay una cosa que no entiendo. Después de varias selecciones de la hora de inicio, la hora predeterminada de la hora de finalización no se actualiza. Se necesitan dos clics para actualizar. Si solo haga clic una vez, haga clic en Aceptar inmediatamente. El límite de tiempo para hacerlo no es válido, como se muestra en la figura
inserte la descripción de la imagen aquí

No descubrí por qué, así que hice un límite en el evento de cambio del tiempo final (más problemático)

 methods: {
    
    
    //控制结束时间大于开始时间
    endTimeChange(val){
    
    
      if(!this.bgnDate){
    
    
        this.$message('请先选择开始时间')
        this.endDate = ''
        return
      }
      //通过比较时间戳,如果结束时间小与开始时间
      if(new Date(val).getTime()<=new Date(this.bgnDate).getTime()){
    
    
        let year = new Date(val).getFullYear();//年
        let month = new Date(val).getMonth();//月
        let day = new Date(val).getDate();//日
        let hours = new Date(this.bgnDate).getHours();//时
        let min = new Date(this.bgnDate).getMinutes();//分
        let second = new Date(this.bgnDate).getSeconds()+1;//秒

//取已选择的结束时间的日期,和已选择的开始时间的时刻秒数+1,实现结束日期一定大于开始日期
        let time =  year.toString() +'-'+
                ((month + 1) > 9 ? (month + 1).toString() : "0" + (month + 1).toString()) +'-'+
                (day > 9 ? day.toString() : ("0" + day).toString())  
              + " " +
              (hours > 9 ? hours.toString() : ("0" + hours).toString()) + ":" +
              (min > 9 ? min.toString() : ("0" + min).toString()) + ":" +
              (second > 9 ? second.toString() : ("0" + second).toString());
//转化成需要的格式 
        this.endDate = new Date(time)
      }
    },
 }

Hasta ahora, el requisito se ha cumplido, y espero que algún día sepa dónde me equivoqué.

Supongo que te gusta

Origin blog.csdn.net/buukyjmvni/article/details/131227720
Recomendado
Clasificación