I have a React app using Material-UI's KeyboardTimePicker
The KeyboardTimePicker has a default value set at "June 10 2021 at 12:00"
If I use the picker popup to change the time, it works fine.
But if I use the textfield to modify the time, it also changes the date to the current date.
https://codesandbox.io/s/keyboardtimepicker-bug-zqeh4?file=/src/App.tsx
How can I ensure that only the time changes when the user uses the keyboard to change the time?
thank you
[Edit] The problem also exists in material-ui Next.
https://github.com/mui-org/material-ui/issues/26799
https://codesandbox.io/s/keyboardtimepicker-bug-material-ui-next-mbmy6
You can achieve that outcome by using the setHours()
getHours()
getMinutes()
.etc. methods that come with the Date object.
I have made a solution that does what you intend to do, which is only to change the hours and the minutes of your state by using the aforementioned methods.
const changeTimeOnly = useCallback(
(time: Date | null) => {
if (time) {
if (!isNaN(time.getHours()) && !isNaN(time.getMinutes()))
handleDateChange((date) => {
if (date) {
date.setHours(time.getHours(), time.getMinutes());
return new Date(date);
}
return null;
});
}
},
[handleDateChange]
);
Keep in mind that the time you print, might be different than the time the timepicker sets depending on your local timezone.