Search code examples
reactjsreact-datepicker

Timestamp format is not supporting the React `react-datepicker` as default value


My date-time format from the api result is 2019-12-30T06:16:48.453Z. It is not supported by the react-datepicker.

My code is following and is a functional component. I didn't write the complete code below. Added just the required parts.

import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

<DatePicker
    selected={'2019-12-30T06:16:48.453Z'}
    {...props}
/>

I also tried adding moment by importing it and used as selected={moment('2019-12-30T06:16:48.453Z')}

I'm getting the error in both cases like Maximum update depth exceeded.


Solution

  • Still version 1.8 of react datepicker they were using moment, to reduce the package size they are using the native Date Objects. reference

    So you can update your code as shown below

     function App() {
      return (
        <div className="App">
          <DatePicker selected={new Date("2019-12-30")} />
          <DatePicker selected={new Date("2019-12-30T06:16:48.453Z")} />
        </div>
      );
    }
    

    working codesandbox

    Update

    to get the required format react datepicker has a prop called dateFormat, so you can add like this dateFormat="dd/MM/yyyy", See here