Search code examples
reactjsdatepickerreact-datepicker

React datepicker - invalid time value


I am trying to create a React-datepicker; however, I am getting this error:

RangeError: Invalid Time Value

I added a dateFormat to match my date variable; however, I am still getting the same error?

What am I doing wrong?

import DatePicker from "react-datepicker";

let date = moment(dateString).format('MMMM d, YYYY h:mm a'); // January 3, 2019 12:30 pm

<DatePicker
    selected={date}
    onChange={this.handleInputChange}
    showTimeSelect
    timeFormat="HH:mm"
    timeIntervals={15}
    dateFormat="MMMM d, YYYY h:mm a"
    timeCaption="time"
/>

I have tried dateFormat="MMMM d, yyyy h:mm aa" as well.


Solution

  • A DatePicker expects a Date, not a moment. You have to convert it first:

    let date = moment(dateString).toDate();
    

    From the DatePicker docs:

    Up until version 1.8.0, this package was using Moment.js. Starting v2.0.0, we switched to using native Date objects to reduce the size of the package. If you're switching from 1.8.0 to 2.0.0 or higher, please see the updated example above of check out the examples site for up to date examples.