I am using react-flatpickr
library as a date picker for my project. The problem using the library is, if I select any date it always considers time as 00:00:00
. Because of such behaviour it creates problem when users from different timezone saves the date.
Is there any way to pass user's local time as well when user selects the date?
I also looked into enableTime: true
which allows to pick time as well. This option also, doesn't have any way to set current time.
Here is my code.
const options = {
enableTime: false,
dateFormat: 'd-m-Y'
};
<Flatpickr
placeholder="Select date"
ref={datepickerRef}
options={options}
value={props.field.value ? props.field.value : ''}
onChange={(date) => {
let selectedDate = new Date(date[0]);
props.form.setFieldTouched(props.field.name);
props.form.setFieldValue(props.field.name, selectedDate);
}}
/>
At 06:41 PM,
Output: Fri Oct 11 2019 00:00:00 GMT+0530 (India Standard Time)
Expected Output: Fri Oct 11 2019 18:41:00 GMT+0530 (India Standard Time)
As the library does not support that format we can set custom time to selected date using setHours(hours,min,sec)
native method.
Get current time and set those values to your selected date
<Flatpickr
placeholder="Select date"
ref={datepickerRef}
options={options}
value={props.field.value ? props.field.value : ''}
onChange={(date) => {
let selectedDate = date[0];
let currentDate = new Date();
let selectedDateWithCurrentTime = new Date(
selectedDate.setHours(currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds())
);
console.log('selectedDateWithCurrentTime',selectedDateWithCurrentTime); // Fri Oct 11 2019 19:47:53 GMT+0530 (India Standard Time)
props.form.setFieldTouched(props.field.name);
props.form.setFieldValue(props.field.name, selectedDateWithCurrentTime.toISOString());
}}
/>
Check example here https://codesandbox.io/s/flatpicker-with-current-time-txdsx