0

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

  • 1
    Does this answer your question? [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Heretic Monkey Oct 06 '20 at 20:14

2 Answers2

1

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
}
casieber
  • 7,264
  • 2
  • 20
  • 34
  • The accepted answer on your linked "duplicate" is not the best answer for this user's use case. It is overly complex. – casieber Oct 06 '20 at 20:16
  • 2
    Ah yes, Stack Overflow, the site I come to when I want to read through 56 answers and decide on the best one when I didn't know the answer in the first place. How user friendly. – casieber Oct 06 '20 at 20:27
  • Sure, you'd rather them go through thousands of duplicate questions, each with slightly different answer, and having the same person try to figure out which one is better. Yeah, no, much more user friendly. – Heretic Monkey Oct 06 '20 at 20:30
  • UTC string => DD/MM/YYYY is a different question than Date instance => DD-mon-YYYY. You or I may understand the inherent similarities in the question and know how to convert one problem into another, but someone asking this type of question may not even know how to go from UTC string => Date. – casieber Oct 06 '20 at 21:16
  • If you spent half the time you spent on these comments actually looking for similar questions, you'd find there are hundreds of questions about dates, strings containing dates, etc. on Stack Overflow. For instance, [Convert Date from one format to another format in JavaScript](https://stackoverflow.com/q/26500694/215552) – Heretic Monkey Oct 06 '20 at 22:20
0

You can use momentjs.

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

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

BeaST 30
  • 696
  • 1
  • 10
  • 22