Can use react-admin DateInput to change the format like dd/MM/yyyy to MM/dd/yyyy

Viewed 2926

The component

<DateInput
  options={{ format: "MM/DD/YYYY", clearable: true }}
  className="location-input" label="Purchase Date" source="PurchaseDate" 
  validate={validatePurchaseDate}
/>
2 Answers

From the doc, you can format the input/output of the component using the format and parse exposed method:

const dateFormatter = v => {
  // v is a `Date` object
  if (!(v instanceof Date) || isNaN(v)) return;
  const pad = '00';
  const yy = v.getFullYear().toString();
  const mm = (v.getMonth() + 1).toString();
  const dd = v.getDate().toString();
  return `${yy}-${(pad + mm).slice(-2)}-${(pad + dd).slice(-2)}`;
};

const dateParser = v => {
  // v is a string of "YYYY-MM-DD" format
  const match = /(\d{4})-(\d{2})-(\d{2})/.exec(v);
  if (match === null) return;
  const d = new Date(match[1], parseInt(match[2], 10) - 1, match[3]);
  if (isNaN(d)) return;
  return d;
};

<DateInput source="isodate" format={dateFormatter} parse={dateParser} />

Reference: https://marmelab.com/react-admin/Inputs.html#transforming-input-value-tofrom-record

If this is the exact and only change you are after - you can use the locale setting with the follwoing values:

  • "en-US": MM/dd/yyyy
  • "en-GB": dd/MM/yyyy

It's kind of a hack but also a painless easy solution.

Related