Craig
Craig

Reputation: 18694

Date string to date object

I am getting a data from my API in the following format:

2019-08-22T00:00:00

I am trying to use the ReactJS Datepicker component found here: https://reactdatepicker.com/#example-1

I am trying to have a data picker (Date only) display this date.

As soon as I set the date, I get an invalid date error. I note that when I select a date, and save it to my state, the date is an object. But I am trying to send it a string.

Do I need to convert the string fromt he API, into a Date object somehow?

render() {
        const format = "dd MMM yyyy"

        return (
            <React.Fragment>
                <div className="labelStyle">
                    {this.props.label}
                </div>
                <div>
                    <DatePicker className="form-control"
                        dateFormat={format}
                        selected={this.props.value}
                        onChange = {this.props.onChange}
                        placeholder={`${dateFnsFormat(new Date(), format)}`}
                    />
                </div>
                <div className="hintStyle">
                    {this.props.help}
                </div>
            </React.Fragment>
        )
    }

Upvotes: 1

Views: 177

Answers (1)

felixmosh
felixmosh

Reputation: 35503

In order to convert your API date to date object, just use the Date constructor.

new Date('2019-08-22T00:00:00');

After a selection, you will receive a Date object as well, when you send it to your API, call the Date's .toISOString() to get a String representation.

Upvotes: 1

Related Questions