Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Doc] Fix DateInput example of format and parse with Date object as value #7233

Merged
merged 1 commit into from
Feb 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 30 additions & 16 deletions docs/Inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -2449,26 +2449,40 @@ Say the user would like to input values of 0-100 to a percentage field but your
`<DateInput>` stores and returns a string. If you would like to store a JavaScript Date object in your record instead:

```jsx
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 dateFormatRegex = /^\d{4}-\d{2}-\d{2}$/;
const dateParseRegex = /(\d{4})-(\d{2})-(\d{2})/;

const convertDateToString = value => {
// value is a `Date` object
if (!(value instanceof Date) || isNaN(value.getDate())) return '';
const pad = '00';
const yyyy = value.getFullYear().toString();
const MM = (value.getMonth() + 1).toString();
const dd = value.getDate().toString();
return `${yyyy}-${(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;
const dateFormatter = value => {
// null, undefined and empty string values should not go through dateFormatter
// otherwise, it returns undefined and will make the input an uncontrolled one.
if (value == null || value === '') return '';
if (value instanceof Date) return convertDateToString(value);
// Valid dates should not be converted
if (dateFormatRegex.test(value)) return value;

return convertDateToString(new Date(value));
};

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

<DateInput source="isodate" format={dateFormatter} parse={dateParser} />
<DateInput source="isodate" format={dateFormatter} parse={dateParser} initialValue={new Date()} />
```

### Linking Two Inputs
Expand Down