core114
core114

Reputation: 5325

react ant design date time picker select date option issue

Im using ant design 3 date time picker for my react project, and im disabled the when the user select the date/time of present/future, and disable all the past dates, its working good, but i have some conflict on that my function.

here the conflict

when i select future date and time after display again select date button on the footer so im select again today date, display the future time with today date , any solution for disable select date button link

you can understand my conflict, please use the stack blitz

here my code

interface AppProps { }
interface AppState {
  name: string; 
  date: Date;
}

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React',
      date: new Date()
    };
  }
//date disable
    disabledDate(current: any) {
        // Can not select days before today and today
        //return current && current < moment().endOf('day');
        return current && current < moment().startOf("day")
    }

    //time disable
    getDisabledHours() {
        var hours = [];
        for (let i = 0; i < moment().hour(); i++) {
            hours.push(i);
        }
        return hours;
    }

    //time disable
    getDisabledMinutes = (selectedHour: any) => {
        var minutes = [];
        if (selectedHour === moment().hour()) {
            for (var i = 0; i < moment().minute(); i++) {
                minutes.push(i);
            }
        }
        return minutes;
    }
  render() {
    return (
      <div>
        <DatePicker
   name="Date" disabledDate={this.disabledDate}
   onChange={d => this.setState({date: d})}
   style={{width: "100%"}}
   showTime={{ disabledMinutes: moment().date() < moment(this.state.date).date() ? undefined : this.getDisabledMinutes, 
   disabledHours: moment().date() < moment(this.state.date).date() ? undefined : this.getDisabledHours}}
   value={moment(this.state.date)}

  />
      </div>
    );
  }
}

Upvotes: 1

Views: 2714

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

What i can do is create a new function to handle the date change

setSelectedDate = (date: any) => {
  const now = moment();  //get current date time
  const isFuture = date.isAfter(now); //check selected date is a future date compared to current date and time
  this.setState({date: isFuture ? date: now.toDate()}); //if it's a future date then assign the slected date else select the current date and time
}

and change the onChange props as

<DatePicker
   name="Date" disabledDate={this.disabledDate}
   onChange={d => this.setSelectedDate(d)}
.....

Here is the updated stackblitz

Upvotes: 2

Related Questions