skip to Main Content

This could be my newness to MUI – however I have a basic (ie no content application)

import React from "react";
import { Container, Grid, Typography } from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";

function App({ children }) {
  // const [value, setValue] = (React.useState < Date) | (null > new Date());

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Container maxWidth="lg">
        <Typography variant="h4" gutterBottom>
          TITLE
        </Typography>
        <Grid container spacing={3}>
          <Grid item xs={4}>
            Please select a date using the picker:
            <DatePicker minDate={new Date("2020-31-12")} />
          </Grid>

          <Grid item xs={8}>
            <Typography variant="body1">
              This is the second (narrower) column. You can add your content
              here.
            </Typography>
          </Grid>
        </Grid>
      </Container>
    </LocalizationProvider>
  );
}

export default App;

I wanted a Datepicker to not show dates before a certain point – I wanted to try anything before 2012, so I put in 2012-01-01 into the date picker and I get a
Uncaught TypeError: value.isAfter is not a function
so I reverted to the code above and this shows me a date picker, but I can see every date back to 1900. I was expected the minDate to not show anything before the entered date, is my assumption incorrect?

(also why does 2012-01-01 cause an error?)

2

Answers


  1. I believe you are getting this error as you must provide the full date object (1995-12-17T03:24:00) if you are using this format in the Date() constructor.
    However you have various options if you check this page

    I could not get it to work using the minDate prop, however did manage to find this solution using shouldDisableDate:

    <DatePicker shouldDisableDate={
      (day) => {
        let check = new Date('2023, 9, 7').valueOf()
        return (day.valueOf() < check) ? true :  false
      }} 
    />
    

    This will prevent the user from selecting any date before 7 September 2023.
    The date constructor is used in this way: new Date(year, monthIndex, day) in this example.
    Of course you can not trust the user and will need to have some server side check to ensure that they do not play around with the JS locally.

    Login or Signup to reply.
  2. use dayjs library. which is used by AdapterDayjs.

    import dayjs from "dayjs"

    <DatePicker minDate={dayjs("2020-31-12")} />

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search