hisusu32
hisusu32

Reputation: 447

ReactJs - Formatting date and time

I have using react datepicker found here: https://www.npmjs.com/package/react-datepicker

My field looks like this:

<DatePicker
    selected={this.state.startDate}
    onChange={this.handleChangeDate}
    dateFormat="yyyy-MM-dd"
/>

My handle looks like this:

handleChangeDate = date => {
    this.setState({
        startDate: date
    });
    console.log('Start Date:' + this.state.startDate)
    this.FormatDate()
};

When selecting todays date my console in the handle gives me this:

Mon Jun 29 2020 15:36:30 GMT-0700 (Pacific Daylight Time)

The datepicker I have in a form, when saving the form it for some reason gets stored like this:

2020-06-29T20:46:42Z

How can I format the startDate to something like this 6/29/2020 3:45PM. I'm trying to use a library called momentjs found here: https://momentjs.com/ . I don't need to use this library if there was a better way, but here is what I have so far:

FormatDate() {
    console.log('In moment loop' + this.state.startDate);
    let FormatstartDate = moment(this.state.startDate).format("yyyy-MM-dd");
    console.log('Moment' + FormatstartDate);
}

Upvotes: 0

Views: 227

Answers (1)

KushalSeth
KushalSeth

Reputation: 4639

copied the description from react-datepicker git repository. Use this latest of react-datepicker to replace momentjs.

Repo link: https://github.com/Hacker0x01/react-datepicker

Up until version 1.8.0, this package was using Moment.js. Starting v2.0.0, we switched to using date-fns, which uses 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.

or you can directly use JavaScript to do this:

var ts = new Date("2020-06-29T20:46:42Z").toLocaleDateString('en-ca');

You can use ECMAInternationalAPI as well to convert the datetime format. How to format a JavaScript date

Upvotes: 1

Related Questions