Search code examples
reactjsreact-datepicker

React Datepicker is sending value as string insteadl of YYYY-mm-dd


I am using react date picker with react hook form and my code looks like:

<Controller
    control={control}
    name="release_date"
    render={({
        field: { onChange, onBlur, value, ref },
    }) => (
        <ReactDatePicker
            onChange={onChange}
            onBlur={onBlur}
            selected={value}
            className="form-control w-full"
            dateFormat="yyyy-MM-dd"
        />
    )}
/>  

It shows as this date on the field 2022-02-15 but its sending data as Tue Feb 15 2022 00:00:00 GMT+0545 (Nepal Time) Instead of this how could I send as yyyy-mm-dd without using any additional packages?


Solution

  • if you really need it, you can use this away:

    create convert function:

    const convert = (selected) => {
        const day = selected.getDate();
        const month =
          selected.getMonth() >= 10
            ? selected.getMonth() + 1
            : `0${selected.getMonth() + 1}`;
        const year = selected.getFullYear();
    
        return `${year}/${month}/${day}`;
      };
    

    change your code:

    <ReactDatePicker
       onChange={onChange}
       onBlur={onBlur}
       selected={convert(value)}
       className="form-control w-full"
       dateFormat="yyyy-MM-dd"
    />