LucasCastellini
LucasCastellini

Reputation: 3

How to format date in ReactJS

I'm getting my backend date as follows:

2020-01-01T03:00:00.000Z

I am using the daterangepicker from the AdminLTE template.

my field:

<div className="col-sm-3">
  <label>Contratação *</label>
  <Field
    name="dt_contracting"
    type="date"
    className="form-control"
  />
</div>

I want to convert the received date, to the format "DD/MM/YYYY"

input in insert

my input is already in the correct format to select, but when I receive the Back-End date, it is not filled due to difference in format.

input in editing

Upvotes: 0

Views: 2393

Answers (2)

casieber
casieber

Reputation: 7542

Easiest way is to use the built-in toLocaleDateString() function. MDN

In your case you can use it like this:

function toPrettyDate( rawDateStr ) {
    const date = new Date( rawDateStr );
    return date.toLocaleDateString('en-GB'); // Should really use user-based locale here
}

Upvotes: 2

BeaST 30
BeaST 30

Reputation: 744

You can use momentjs.

Prefer this for installation https://www.npmjs.com/package/react-moment

https://momentjs.com/docs/ for examples

Upvotes: 0

Related Questions