AntDesign DatePicker 控件日期时间禁用问题

一、设置日期只能选择当前日期及以后的日期

const disabledDate = (current: any) => {
   return current && current < moment().subtract(1, 'days').endOf('day');
}

二、设置只能选择今天的当前时间以后的时间(今天)

const range = (start: any, end: any) => {
    const result = [];
    for (let i = 0; i < start; i++) {
      result.push(i);
    }
    return result;
}


const disabledDateTime = (dates: any) => {
    let hours = moment().hours();//0~23
    let minutes = moment().minutes();//0~59
    // let seconds = moment().seconds();//0~59
    if (dates && moment(dates).date() === moment().date()) {
      return {
        disabledHours: () => range(hours, 24),
        disabledMinutes: () => range(minutes, 60),
        // disabledSeconds: () => range(seconds + 1, 59),
      };
    }
    return {
      disabledHours: () => [],
      disabledMinutes: () => [],
      // disabledSeconds: () => [],
    };
}

三、设置只能选择当前时间以前的时间(今天)

  const range0 = (start: any, end: any) => {
    const result = [];
    for (let i = start; i <= end; i++) {
        result.push(i);
    }
    return result;
  }


  //当日只能选择当前时间之后的时间点
  const disabledTime = (date: any) => {
    let currentDay = moment().date();    //当下的时间
    let currentHours = moment().hours();
    let currentMinutes = moment().minutes();  //设置的时间
    let settingHours = moment(date).hours();
    let settingDay = moment(date).date();
    if (date && settingDay === currentDay && settingHours === currentHours) {
      return {       
        disabledHours: () => range0(0, currentHours-1),         //设置为当天现在这小时,禁用该小时,该分钟之前的时间
        disabledMinutes: () => range0(0, currentMinutes-1),
      };
    }else if (date && settingDay === currentDay && settingHours > currentHours) {
      return { 
        disabledHours: () => range0(0, currentHours-1),      //设置为当天现在这小时之后,只禁用当天该小时之前的时间 
      };   
    }else if (date && settingDay === currentDay && settingHours < currentHours) {
      return {
        disabledHours: () => range0(0, currentHours-1),      //若先设置了的小时小于当前的,再设置日期为当天,需要禁用当天现在这小时之前的时间和所有的分
        disabledMinutes: () => range0(0, 59),
      }
    }else if (date && settingDay > currentDay) {
      return {                                    
        disabledHours: () => [],                     //设置为当天之后的日期,则不应有任何时间分钟的限制
        disabledMinutes: () => [],
      }
    }
    return {                                    
      disabledHours: () => [],                     //设置为当天之后的日期,则不应有任何时间分钟的限制
      disabledMinutes: () => [],
    }
  }

使用方法:

 <DatePicker
                  style={
   
   { width: '100%' }}
                  showTime
                  onChange={() => {}}
                  format="YYYY-MM-DD HH:mm"
                  placeholder="选择日期时间"
                  disabledDate={disabledDate}
                  disabledTime={disabledDateTime}
/>

效果:

猜你喜欢

转载自blog.csdn.net/weixin_42333548/article/details/128118322