1

My datepicker is throwing RangeError: Invalid time value while trying to set selected date value which i am getting from API as string value.

My API date string is 12.09.2020

<DatePicker dateFormat="dd/MM/yyyy" selected={currentFuelPrice.date_of_sale} onChange={date => setStartDate(date)} />

After react 2.0 version, datepicker wont support date as string, it said to use date-fns parseiso...

import { parseISO } from 'date-fns'; 

currentFuelPrice.date_of_sale = parseISO(response.data.date_of_sale, 1);

after adding parseISO, i am still getting error RangeError: Invalid time value

5
  • Which version are you using ? Commented Sep 14, 2020 at 6:34
  • Which version of DatePicker are you using ? Commented Sep 14, 2020 at 6:36
  • react version 16.13.1 Commented Sep 14, 2020 at 6:37
  • datepicker 3.1.3 Commented Sep 14, 2020 at 6:39
  • did you do this: selected={Date.parse('12/09/2020')} ? Commented Sep 14, 2020 at 6:40

1 Answer 1

2

You can use parse method to achieve your goal. It's accepting date string, format and reference date. Here you can use like this:

Codesandbox: https://codesandbox.io/s/heuristic-feynman-k75i4?file=/src/App.js:0-639

import React, { useState } from "react";
import "./styles.css";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { parse } from "date-fns";

export default function App() {
  const [startDate, setStartDate] = useState(new Date());

  return (
    <div className="App">
      <DatePicker
        dateFormat="dd/MM/yyyy"
        selected={startDate}
        onChange={(date) => setStartDate(date)}
      />
      <button
        onClick={() =>
          setStartDate(parse("12.09.2020", "dd.MM.yyyy", new Date()))
        }
      >
        Set Api DATE
      </button>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

it is working perfectly. after adding parse method..it was my mistake not added startdate to datepicker as selected value..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.