I'm using React Date Picker and I have a problem that time is selected as 12:00 am automatically when I select date even though the time is passed already. I don't know why the default value of time is 12:00. I've searched but I don't know how to fix the problem. Is there a way that selecting the time to be required? or set time value as null
function ReservationCalander() {
const [startDate, setStartDate] = useState(false);
const [endDate, setEndDate] = useState(false);
const [isStartDateSelected, setIsStartDateSelected] = useState(
false,
);
const maxEndDate = new Date(startDate).setDate(
new Date(startDate).getDate() + 1,
);
const booked = '2022-11-26T02:00:00.000Z';
const handleStartDate = time => {
setIsStartDateSelected(time);
setStartDate(time);
setEndDate(false);
};
const handleDisabledEndTime = time => {
const selectedDate = new Date(time);
return (
new Date(startDate).getTime() < selectedDate.getTime() &&
selectedDate.getTime() <= new Date(maxEndDate).getTime()
);
};
const handleFilterPassedTime = time => {
const currentDate = new Date();
const selectedDate = new Date(time);
return currentDate.getTime() < selectedDate.getTime();
};
return (
<Container>
<DatePick marginBottom="8px">
<Label>시작일시</Label>
<DatePicker
selectsStart
showTimeSelect
selected={startDate}
onChange={handleStartDate}
startDate={startDate}
endDate={endDate}
minDate={new Date()}
locale={ko}
dateFormat="yyyy년 MM월 dd일 a hh시"
timeIntervals={60}
placeholderText="스케줄을 선택하세요"
filterTime={handleFilterPassedTime}
className="calander"
disabledKeyboardNavigation
excludeTimes={[new Date(booked)]}
/>
</DatePick>
<DatePick>
<Label>종료일시</Label>
<DatePicker
selectsEnd
showTimeSelect
selected={endDate}
onChange={date => setEndDate(date)}
startDate={startDate}
endDate={endDate}
minDate={startDate}
maxDate={maxEndDate}
locale={ko}
dateFormat="yyyy년 MM월 dd일 a hh시"
timeIntervals={60}
placeholderText="스케줄을 선택하세요"
filterTime={handleDisabledEndTime}
disabled={!isStartDateSelected}
disabledKeyboardNavigation
/>
</DatePick>
</Container>
);
}
This bothered me too.
I ended up making the value displayed in the filed different from the selected value (which is the full date object).
Most of this is achieved in the onChange. Note that mine is wrapped in a formik form, so that's why i'm using field.value etc. So you'll have to adjust if you're not using formik.
onchange function defintion:
const handleDateChange = (val, fieldName) => {
const date = new Date(val)
const month = (date.getMonth() + 1).toString().padStart(2, '0')
const day = date.getDate().toString().padStart(2, '0')
const year = date.getFullYear().toString()
const formattedDate = `${month}/${day}/${year}`
setFieldValue(fieldName, formattedDate) // set the date field to the formatted date
}
And I have my params for the <DatePicker like so:
<DatePicker
value={field.value ? field.value.toString() : undefined}
selected={field.value ? new Date(field.value) : null}
onChange={(val) => {
handleDateChange(val, field.name)
}}
...other params
/>