Geeting value differance in MUI date picker - javascript

I am using Mui 5 date picker my issue is if I change the date using calendar I will get the expected result like the example I selected 26 I get this
"2022-01-26T09:16:10.000Z"
but when I edit directly in the field example I selected 27 I get this
"2022-01-26T18:30:00.000Z" because of this I will get a validation error I am not understanding why this happening and after the edit, if the select date from again calendar 26 then the final value is
"2022-01-25T18:30:00.000Z"
for external I am using momentjs and fromik.
const [value, setValue] = React.useState(null);
return (
<Box>
{JSON.stringify(value)}
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</Box>
);

Using moment, set the initial value to start of the day startOf.
const [value, setValue] = React.useState(moment().startOf('day'))
Code snippet:
export default function BasicDatePicker() {
const [value, setValue] = React.useState(moment().startOf('day'));
return (
<LocalizationProvider dateAdapter={AdapterMoment} >
<DatePicker
label="Basic example"
value={value}
onChange={(newValue) => {
setValue(moment(newValue));
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
);
}
Sandbox : here
EDIT:
if you have a specific date to be passed,
React.useState(moment('03-03-2021').startOf("day"))

Related

DateTimePicker seems to be an hour off?

I have the following code in my React application:
import { DateTimePicker, LocalizationProvider } from "#mui/x-date-pickers";
import { AdapterMoment } from "#mui/x-date-pickers/AdapterMoment";
import moment from "moment";
...
const [job, setJob] = useState({
name: "",
outgoingDateTime: moment("2022-09-01T21:00:00"),
});
const handleOutgoingDateTimeChange = (newValue) => { setJob({...job, outgoingDateTime: newValue}); }
...
<LocalizationProvider dateAdapter={ AdapterMoment }>
<Stack spacing={2} direction="row">
<DateTimePicker
label="Outgoing Date and Time"
value={ job.outgoingDateTime }
onChange={ handleOutgoingDateTimeChange }
inputFormat="DD/MM/YYYY HH:mm"
ampm={ false }
renderInput={(params) => <TextField {...params} />} />
</Stack>
</LocalizationProvider>
When I then enter something like 2022-09-13T21:05:00.000Z into the DateTimePicker and then submit and output the result, I have this:
Job Outgoing Date Time: "2022-09-13T20:05:00.000Z"
Which is clearly an hour behind what I've tried to submit which is not what I want as I asked for 21:05 for example. How can I fix this to show the correct time when I submit it?

Material UI (MUI) date picker with react-hook-form

I'm creating a form which has a date field. I'm using MUI and react-hook-form for validation. I've tried to render the field in two different ways, but when submitting my form I'm not getting the expected value:
Render 1
Using a Controller component:
const [originalReleaseDate, setOriginalReleaseDate] = useState(null);
<Controller
name={"original_release_date"}
defaultValue={originalReleaseDate}
control={control}
render={({field}) =>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Original Release Date"
value={originalReleaseDate}
onChange={(newValue) => {
setOriginalReleaseDate(newValue);
}}
renderInput={(params) =>
<TextField
{...params}
/>}
/>
</LocalizationProvider>
}
/>
when I render the field this way, I'm getting null for original_release_date after submitting the form.
Render 2
Registering the field directly using {...register("reissue_release_date")} instead of react-hook-form Controlled component.
const [reissueReleaseDate, setReissueReleaseDate] = useState(null);
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Reissue Release Date"
value={reissueReleaseDate}
onChange={(newValue) => {
setReissueReleaseDate(newValue);
}}
renderInput={(params) =>
<TextField
{...params}
{...register("reissue_release_date")}
/>}
/>
</LocalizationProvider>
this way is working half way. If I manually type the date then I'm getting its value on submit, BUT if I use the date picker and then submitting the form I get "".
Any idea what's going on?
Just modified the above answer with a bracket.
const [reqDate, setreqDate] = useState(new Date());
<Controller
name="reqDate"
defaultValue={reqDate}
control={control}
render={
({ field: { onChange, ...restField } }) =>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Request Date"
onChange={(event) => { onChange(event); setreqDate(event); }}
renderInput={(params) =>
<TextField
{...params}
/>}
{...restField}
/>
</LocalizationProvider>
}
/>
InputDate.propTypes = {
name: PropTypes.string,
label: PropTypes.string,
};
export default function InputDate({ name, label }) {
const { control } = useFormContext();
return (
<Controller
name={name}
control={control}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<LocalizationProvider dateAdapter={AdapterMoment} >
<DesktopDatePicker
label={label}
control={control}
inputFormat="DD-MM-YYYY"
value={value}
onChange={(event) => { onChange(event); }}
renderInput={(params) => <TextField {...params} error={!!error} helperText={error?.message} />}
/>
</LocalizationProvider>
)} />
)
}
In most cases, if you are using react-hook-form, you don't need to track form fields with useState hook.
Using a Controller component is the right way to go. But there is a problem with onChange handler in your 1st method.
When you submit form, you are getting default date null because field is destructed, but it's not passed to DatePicker. So, onChange prop of field is not triggered when date is changed and react-hook-form doesn't have new date.
Here's how your render method should be
render={({field}) =>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Original Release Date"
renderInput={(params) =>
<TextField
{...params}
/>}
{...field}
/>
</LocalizationProvider>
}
If for some reason, you need to update component state then you have to send data to react-hook-form and then update local state
render={({field: {onChange,...restField}) =>
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Original Release Date"
onChange={(event) => {
onChange(event);
setOriginalReleaseDate(event.target.value);
}}
renderInput={(params) =>
<TextField
{...params}
/>}
{...restField}
/>
</LocalizationProvider>
}
I couldn't replicate your setup, but my guess is that in the first render the
reference to the 'setOriginalReleaseDate' is lost when being passed through the Controller's render arrow function.
...
onChange={(newValue) => {
setOriginalReleaseDate(newValue);
}}
...
so, try putting the logic in a defined function like:
const handleOriginalReleaseDateChange = (newValue) => {
setOriginalReleaseDate(newValue);
};
and change the onChange to call the function.
...
onChange={handleOriginalReleaseDateChange}
...

MUI Datepicker how to disable next month only

I'm using MUI v5 and I want to disable next month only in datepicker. Others are available
import moment from 'moment';
const isNextMonth = (date) = {
const startOfNextMonth = moment().add(1, 'month').startOf('month');
const endOfNextMonth = moment().add(1, 'month').endOf('month');
return date >= startOfNextMonth && date <= endOfNextMonth;
};
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
views={['year', 'month', 'day']}
label={label}
shouldDisableDate={isNextMonth}
value={value}
onChange={handleChange}
renderInput={(params) => <TextField {...params} helperText={null} />}
/>
</LocalizationProvider>

unable to show error and error message on MUI datepicker

I'm using react material-ui (MUI)
I want to show an error on some condition that will calculate on the backend.
I used MUI-datepicker but I can't show error
import * as React from 'react';
import TextField from '#mui/material/TextField';
import AdapterDateFns from '#mui/lab/AdapterDateFns';
import LocalizationProvider from '#mui/lab/LocalizationProvider';
import DatePicker from '#mui/lab/DatePicker';
const PickupDatePickerComponent = (props) => {
const [value, setValue] = React.useState(null);
const handleChange = (newValue)=>{
setValue(newValue);
}
const todayDate = new Date();
return (
<LocalizationProvider style={{ width:"100%"}} dateAdapter={AdapterDateFns}>
<DatePicker
label="example"
value={value}
onChange={handleChange}
minDate={todayDate}
renderInput={(params) => <TextField
error
helperText="Your error message"
{...params} sx={{ width:"100%" }}
/>}
onError={true}
error
helperText="Your error message"
/>
</LocalizationProvider>
);
}
export default PickupDatePickerComponent
the error property is not working not in <Input/> nor in <DatePicker/> so the border won't be red... (like normal errors)
Put error attribute after
{...params} sx={{ width:"100%" }}
like this
renderInput={(params) => <TextField
{...params} sx={{ width:"100%" }}
error
helperText="Your error message"
/>}
i passed to onError prop a callback function as recommended in docs , this is a working demo based on your code.

Issue with MUI 5 datePikker when we add inputFormat

what happens if I select a date by clicking on the calendar it works fine but if I set inputFormat="yyyy/MM/dd" then I will type the date it will not react like date format its go like 11111111111111111111 it is considered as a string like this so its break the format of date but if I select from the calendar it works fine but only if I will edit direct type it goes wrong.
<LocalizationProvider dateAdapter={AdapterDateFns}>
<DatePicker
label="Basic example"
value={value}
inputFormat="yyyy/MM/dd"
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
add mask props to your code.
<DatePicker
...
mask="____/__/__"
/>

Categories

Resources