Does not date-fns and Mui DatePicker work together?

84 Views Asked by At

I am in despair. Hopefully someone of you can help me. I am Trying to set up a usual signup page with age controll, but I am getting a problem with the format of the date. Age control works totally fine, but in the last step I would like to have the DOB in 'dd.MM.yyyy'-format. Here is what i am doing:




    const SignUp = () => {

      useEffect(() => {
        const today = parseISO(new Date().toISOString().split("T")[0]);
        const age = differenceInYears(today, dob);
        const newdate = format(new Date(), 'dd.MM.yyyy') //just to check if it works as expected
        console.log('The date is ' + new Date() + ' the type is: ' + typeof(new Date()) + 'is this the correct format? ' + newdate)
        const newdob = format(dob, 'dd.MM.yyyy')
        console.log('The DOB is '+ dob + ' the type is: ' + typeof(dob) + ' the age is: ' + age + ' is this the correct format? ' + newdob );
        const result = DOB_REGEX.test(age);
        setValidDOB(result);
      }, [dob]);

    return (
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <DemoContainer components={["DatePicker"]}>
            <DatePicker
              label="Day of birth"
              fullWidth="true"
              name="dob"
              id="dob"
              format="DD/MM/YYYY"
              required
              autoFocus
              value={dob}
              color={validDOB ? "success" : "error"}
              onInput={handleChange} 
              onChange={(e) => setDOB(new Date(e))} //ISO 8601
              inputRef={userRef}
              onFocus={() => setDOBFocus(true)}
              onBlur={() => setDOBFocus(false)}
            />
          </DemoContainer>
        </LocalizationProvider>
    );
    }
    export default SignUp;

So I have checked if the formatting is working in gerneral. everything is working as expected. But if I use the dob variable like for newdob I always get the error "Invalid time value" eventhough the dates and the type of new Date() and dob are the same. Does anyone have a clue why this error occures in the constallation where I am using the variable from the DatePicker and why it doesnt occures why i am working with new Date()?

0

There are 0 best solutions below