28

I have set up a DatePicker component using the react-datepicker library and am passing it an initial date value calculated using today's date in the MM-DD-YYYY format.

However, when I load the page in React, I get

RangeError: Invalid Time Value

const AuthForm = ({ buttonText, formType, onAuth, history, ...props }) => {

  const startDate = new Date().toLocaleDateString();

  const initialStateSignup = {
      email : "",
      password : "",
      firstName: "",
      lastName: "",
      gender: "",
      dob: startDate
  };
    const [state , setState] = useState(formType === 'login' ? initialStateLogin : initialStateSignup);

  const handleChange = e => {
      const {name , value} = e.target;
      setState( prevState => ({
          ...prevState,
          [name] : value
      }))
  }
  ...
  return (
     <DatePicker
        placeholderText="Date of Birth"
        selected={state.dob}
        onChange={handleChange}
      />
  )

Where is this error coming from? I console logged the startDate and it looks valid to me, and this is the method I have seen documented in other threads for generating the start date.

7 Answers 7

19

According to this post https://github.com/Hacker0x01/react-datepicker/issues/1752 you most probably use old version of datepicker, that also may not be fully consistent with your React environment.

So check your react-datepicker version, if needed upgrade to 2+, and use this syntax:

const selected = moment(isoDateStr).toDate();

This is because react-datepicker before version 2 uses moment object date type directly and version 2+ uses javascript date type instead.

7

Just pass to your DatePicker component dateFormat="MM-DD-YYYY" prop, with your desired format.

https://reactdatepicker.com/#example-7

<DatePicker
  dateFormat="MM-DD-YYYY"
  selected={this.state.startDate}
  onChange={this.handleChange} 
/>

P.D. You would like to use useReducer instead of useState in the case your state is an object.

4

use new Date(this.state.StartDate)

  <DatePicker
  dateFormat="MM-dd-yyyy"
  selected={new Date(this.state.startDate)}
  onChange={this.handleChange} 
  />
0

A combination of Adolfo and Vijay's answers worked for me:

Start Date:<br></br><DatePicker dateFormat="MM-dd-yyyy" selected={new Date()} onChange={(date) => setStartDate(date)} /><br></br>

End Date:<br></br><DatePicker dateFormat="MM-dd-yyyy" selected={new Date()} onChange={(date) => setEndDate(date)} /><br></br>

0

This problem are very simple way to solve. Your reactjs project inside install react datepicker and moment js like

    yarn add react-datepicker
    or npm install react-datepicker
    yarn add moment
    or npm install moment

And import your component page like

    import DatePicker from "react-datepicker";
    import moment from 'moment';
    function Car() {
    const [startDate, setStartDate] = useState(new Date());  
    const slectedDate = moment(yourDate).toDate();
      return (
     <DatePicker
                className="form-control"
                placeholderText="Select date"
                onChange={(date) => field.onChange(date, setStartDate(date))}
                selected={slectedDate }
                dateFormat="yyyy-MM-dd"
              />
);
    }
0
It can be done with react date picker only.

On the loading of page or in componentDidMount() function , you can set the state of date by formatting as using dateformat or be with new Date()

console.log(localStorage.getItem("valuationDate"));
var startDateStore = **dateFormat**(localStorage.getItem("valuationDate"), "dd mmm yyyy");
    console.log(startDateStore);
    
    this.setState({
      startDate: new Date(localStorage.getItem("valuationDate")),
    }); 
-1
import React, { useState } from 'react';
import { format } from 'date-fns';
import { DayPicker } from 'react-day-picker';
import 'react-day-picker/dist/style.css';

const Daypiker = () => {
    const [selected,setSelected]=useState(new Date())
    return (
        <div>
            <DayPicker
            mode='single'
            selected={selected}
           onSelect={(data)=>{
                      if(data){
                      setSelected(data)
                       }}}   
            ></DayPicker>

            <p><p>You selected {format(selected, 'PP')}.</p></p>
        </div>
    );
};

export default Daypiker;
1
  • I stumbled on this problem with a WordPress bespoke gutenberg plugin (thanks @josias) that uses DatePicker. What would be the way to adapt the gb cmeta code to have this working in a swiss-date-format style?
    – theking2
    Feb 3 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.