The elementui time control limits the optional time range (accurate to hours, minutes and seconds)

The elementui time control limits the optional time range (accurate to hours, minutes and seconds)

When we develop web-side projects, time controls are used a lot. Restricting the optional time is also a relatively common requirement. For example, the past time cannot be selected, or the future time cannot be selected, etc. If only the year, month, and day are limited, it is very Easy to solve, what if it is accurate to the hour, minute and second? In fact, it is also very simple. Next, let’s look at my requirements (my requirement is that the past time cannot be selected and must be accurate to the hour, minute, and second). Without further ado, let’s talk about the code:

//我们在vue中的data中定义一个对象,绑定给时间组件
expireTimeOption: {
    
    
   selectableRange:`${
      
      moment().format('HH:mm:SS')} - 23:59:59`,//这里是限制可选时间到时分秒
   //用当前时间减去一整天的时间,得到的就是当前时间到晚上13:59:59的区间
   disabledDate(date) {
    
    //这里是限制可选时间到年月日的
     //disabledDate 文档上:设置禁用状态,参数为当前日期,要求返回 Boolean
     return date.getTime() < Date.now() - 3600 * 1000 * 24;
    },
 },

I thought it would be over like this. One limits the year, month, day, and the other limits the time, minutes, and seconds, but there will be a bug. If it is 8 o'clock in the morning, you cannot choose before 8 o'clock tomorrow. This is obviously wrong. Then How do we solve it? upper code

//使用watch时间监听时间控件的值
watch: {
    
    
    'form.startTime'(selectTime) {
    
    
      const date = moment(selectTime).format('YYYY-MM-DD');
      const today = moment().format('YYYY-MM-DD');
      if (date === today){
    
    //如果选择是日期是当天
         // 先把时间控件的值赋值当前时间
        this.form.startTime = moment().format('YYYY-MM-DD HH:mm:SS')
         //然后限制时间小于此时此刻的时分秒不可选
        this.expireTimeOption.selectableRange = `${
      
      moment().format('HH:mm:SS')} - 23:59:59`
      } else {
    
    //如果选择是日期是明天或者更远的时间
        // 先把时间控件的值赋值为一天的的开始
        this.form.startTime = moment().format('YYYY-MM-DD 00:00:00')
        // 然后把时分秒的限制放开
        this.expireTimeOption.selectableRange = '00:00:00 - 23:59:59'
      }
    },
}

Guess you like

Origin blog.csdn.net/m0_52313178/article/details/126319525