Reputation: 124
I'm using Material UI KeyboardDatePicker for my app, and when I select a date and console.log it at first select date & time are displayed correctly, but if I wait 1-2 minutes and select another date, date will be updated but time will be the same as 1st select. For example, if I select March 26th, date will be displayed as Friday Mar 24 2021 17:49:00 GMT-0400, if I wait 2 minutes and select March 27th, date will be Saturday Mar 24 2021 but time still 17:49:00 GMT-0400 ( although actual time is 17:51:00). My code is:
import "./styles.css";
import React, { useState } from "react";
import { MuiPickersUtilsProvider } from "@material-ui/pickers";
import DateFnsUtils from "@date-io/date-fns";
import { KeyboardDatePicker } from "@material-ui/pickers";
export default function App() {
const [isOpen, setIsOpen] = useState(false);
const [date, setDate] = useState();
const handleDateChange = (date) => {
setDate(date);
};
console.log(date)
return (
<div className="App">
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
style={{ width: 200, height: 28 }}
minDate={new Date()}
disableToolbar={true}
margin="none"
variant="inline"
value={date}
inputVariant="outlined"
emptyLabel="Select Date"
format="MM/dd/yyyy"
onChange={handleDateChange}
KeyboardButtonProps={{
onFocus: (e) => {
setIsOpen(true);
}
}}
PopoverProps={{
disableRestoreFocus: true,
onClose: () => {
setIsOpen(false);
}
}}
InputProps={{
onFocus: () => {
setIsOpen(true);
}
}}
open={isOpen}
/>
</MuiPickersUtilsProvider>
</div>
);
}
and codesandbox
I don't know why time doesn't update each time I select another date. Any help and suggestions are greatly appreciated.
Upvotes: 0
Views: 2698
Reputation: 492
I'm guessing that the component has a unique Date object that is instantiated once. Upon a new day selection, it would manually update year, month and day, preserving the rest of the properties.
You can manually update the hours, minutes and seconds on the change handler
const handleDateChange = (date) => {
const updatedDate = new Date();
date.setHours(updatedDate.getHours());
date.setMinutes(updatedDate.getMinutes());
date.setSeconds(updatedDate.getSeconds());
setDate(date);
};
Upvotes: 1