Search code examples
reactjsmaterial-uitimepicker

React MUI Timepicker - Can't disable specific times


is there a way to disable some hours of the clock? https://mui.com/x/react-date-pickers/time-picker/

minTime={new Date(0, 0, 0, 8)}
maxTime={new Date(0, 0, 0, 18, 45)}

This is how its supposed to work but it's not working for me. Do you know how it works and is there any way to create 2 or more timezones. Bcs it's for a restaurant app and the restaurant is opening at lunch and dinner time...

is not working for me

import React, { useState } from "react";
import {
  DatePicker,
  TimePicker,
  MuiPickersUtilsProvider,
} from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import { createTheme, ThemeProvider } from "@material-ui/core";
import deLocale from "date-fns/locale/de";
const theme = createTheme({
  palette: {
    primary: {
      main: "#eab308",
    },
  },
});
const Datepicker = ({ state, setState }) => {
  const handleDateChange = (date) => {
    setState(date);
  };
  // sunday = 0 ; saturday = 6 date.getDay() === 1 || date.getDay() === 3 disables monday and wednesday
  function disableDays(date) {
    return date.getDay() === 1 || date.getDay() === 3;
  }
  // Dont use state in this case. Otherwise you can abuse date + 1 month and skip it unlimited farward
  const today = new Date();
  return (
    <ThemeProvider theme={theme}>
      <MuiPickersUtilsProvider utils={DateFnsUtils} locale={deLocale}>
        <div className='flex justify-center max-w-[300px] mx-auto'>
          <div className='p-2'>
            <DatePicker
              shouldDisableDate={disableDays}
              value={state}
              onChange={handleDateChange}
              format='dd.MM.yyyy'
              cancelLabel='Abbrechen'
              disablePast
              maxDate={new Date(today.getTime() + 31 * 24 * 60 * 60 * 1000)}
              orientation='landscape'
            />
          </div>
          <div className='p-2'>
            <TimePicker
              value={state}
              onChange={handleDateChange}
              ampm={false}
              minutesStep={5}
              orientation='landscape'
              minTime={new Date(0, 0, 0, 8)}
              maxTime={new Date(0, 0, 0, 18, 45)}
            />
          </div>
        </div>
      </MuiPickersUtilsProvider>
    </ThemeProvider>
  );
};
export default Datepicker;


Solution

  • It is clear from your imports that you use Material-ui v4.
    But You want to use some props from v5 TimePicker

    v4 TimePicker's props does not contain minTime or maxTime,
    v4 TimePicker Documentation: https://v4.mui.com/components/pickers .

    You have to upgrade to Material ui v5
    v5 TimePicker Documentation: https://mui.com/x/react-date-pickers/time-picker .

    Or: You can create custom TimePicker render custom error if time is not in a specific range.
    This will help you: https://github.com/mui/material-ui-pickers/issues/519