Rohit Sawai
Rohit Sawai

Reputation: 839

Throwing error RangeError: Invalid time value while setting custom date to DatePicker of react-datepicker

I'm trying to set selected parameter as default date of DatePicker of react-datepicker. Basically date which I'm getting from database is in following format:

event_date: "2019-06-15"

and when I set state, that date shows in this way - event_date: "2019-06-15T00:00:00"

I have tried to new Date() for converting it into JavaScript compatible date. Also tried MomentJS but then also it's throwing same error. When I call new Date() in selected parameter then everything works perfectly. I mean, DatePicker shows default todays date. But when I try to set custom date value to DatePicker, it throws error - RangeError: Invalid time value.

Can anyone tell me what type of data DatePicker need for setting custom date?

Upvotes: 4

Views: 27908

Answers (4)

Prati
Prati

Reputation: 49

This worked for me.

import { format, parseISO } from "date-fns"; 
<div>{format(parseISO(dateofbirth, 'yyyy-MM-dd', new Date()), "do MMM yyy")}</div>

Upvotes: -1

Jayanth Kumar T
Jayanth Kumar T

Reputation: 317

You can use latest date-fns library in Javascript and use below for format

import { format, parseISO } from 'date-fns' 

format(parseISO(DateinISOformat), "MMM dd h:m a") 

Example below -

format(parseISO('2019-06-15T00:00:00'), "MMM dd h:m a") 

Upvotes: 2

marekful
marekful

Reputation: 15351

React-datepicker requires an instance of Date to be passed for configuration values such as startDate, etc. (or possibly it also excepts timestamp integers, not sure).

You can use

new Date(Date.parse("2019-06-15T00:00:00"));

To create a date instance. Date.parse() recognizes many date string formats and converts them to timestamp values which in turn are accepted by the Date() constructor.

Upvotes: 6

ravibagul91
ravibagul91

Reputation: 20755

It seems your date is in string format. Datepicker don't accept string date.

You need to parse the string date to actual date using parseISO

import { parseISO } from 'date-fns' 

Usage,

parseISO(your_custom_date)

Upvotes: 12

Related Questions