Umbro
Umbro

Reputation: 2204

How to make disabled date and time in react datepicker?

For example: today is August 23 at 4 pm. I make to disabled dates until 22 (I used minDate = {moment ().toDate ()}). How to make disabled time in this case up to 16 (include)? That you cannot choose a date and time earlier than at the present. I use the react-datepicker and moment libraries.

Code here: https://stackblitz.com/edit/react-msygf9

class App extends Component {
  constructor() {
    super();
    this.state = {
      selected: new Date()
    };
  }

  handle = (date) => {
    this.setState({
      selectedDate: date
    })
  }

  render() {
    return (
      <div>
         <DatePicker
            selected={this.state.selected}
            onChange={this.handle}
            showTimeSelect
            timeFormat="HH:mm"
            timeIntervals={15}
            dateFormat="MMMM d, yyyy h:mm aa"
            timeCaption="time"
            minDate={moment().toDate()}
          />
      </div>
    );
  }
}

Upvotes: 4

Views: 8773

Answers (1)

Ray
Ray

Reputation: 325

https://stackblitz.com/edit/react-hogvhv?file=index.js

I have tested this and it works according to what you requested.

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import moment from 'moment';


class App extends Component {
  constructor() {
    super();
    this.state = {
      selected: new Date(),
      minTime: this.calculateMinTime(new Date())
    };
  }
  calculateMinTime = date => {
    let isToday = moment(date).isSame(moment(), 'day');
    if (isToday) {
        let nowAddOneHour = moment(new Date()).add({hours: 1}).toDate();
        return nowAddOneHour;
    }
    return moment().startOf('day').toDate(); 
}

  handle = (date) => {
    this.setState({
      selectedDate: date,
      minTime: this.calculateMinTime(date)
    })
  }

  render() {
    return (
      <div>
         <DatePicker
            selected={this.state.selected}
            onChange={this.handle}
            excludeOut
            showTimeSelect
            timeFormat="HH:mm"
            timeIntervals={15}
            dateFormat="MMMM d, yyyy h:mm aa"
            timeCaption="time"
            minDate={new Date()}
            minTime={this.state.minTime}
            maxTime={moment().endOf('day').toDate()}
          />
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Upvotes: 4

Related Questions