Skip to content

Commit

Permalink
Allow DateField to display only a time
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaudvergnet committed Jul 4, 2022
1 parent 15e7a86 commit 0f79261
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 6 deletions.
15 changes: 15 additions & 0 deletions packages/ra-ui-materialui/src/field/DateField.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ describe('<DateField />', () => {
expect(queryByText(date)).not.toBeNull();
});

it('should render only a time when the showtime prop is true and showdate is false', () => {
const { queryByText } = render(
<DateField
record={{ id: 123, foo: new Date('2017-04-23 23:05') }}
showTime
showDate={false}
source="foo"
locales="en-US"
/>
);

const date = new Date('2017-04-23 23:05').toLocaleTimeString('en-US');
expect(queryByText(date)).not.toBeNull();
});

it('should pass the options prop to toLocaleString', () => {
const date = new Date('2017-04-23');
const options = {
Expand Down
29 changes: 23 additions & 6 deletions packages/ra-ui-materialui/src/field/DateField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,17 @@ export const DateField: FC<DateFieldProps> = memo(props => {
locales,
options,
showTime = false,
showDate = true,
source,
...rest
} = props;

if (!showTime && !showDate) {
throw new Error(
'<DateField> cannot have showTime and showDate false at the same time'
);
}

const record = useRecordContext(props);
if (!record) {
return null;
Expand Down Expand Up @@ -73,13 +81,20 @@ export const DateField: FC<DateFieldProps> = memo(props => {
// who may see a different date when calling toLocaleDateString().
dateOptions = { timeZone: 'UTC' };
}
const dateString = showTime
? toLocaleStringSupportsLocales
let dateString = '';
if (showTime && showDate) {
dateString = toLocaleStringSupportsLocales
? date.toLocaleString(locales, options)
: date.toLocaleString()
: toLocaleStringSupportsLocales
? date.toLocaleDateString(locales, dateOptions)
: date.toLocaleDateString();
: date.toLocaleString();
} else if (showDate) {
dateString = toLocaleStringSupportsLocales
? date.toLocaleDateString(locales, dateOptions)
: date.toLocaleDateString();
} else if (showTime) {
dateString = toLocaleStringSupportsLocales
? date.toLocaleTimeString(locales, options)
: date.toLocaleTimeString();
}

return (
<Typography
Expand All @@ -103,6 +118,7 @@ DateField.propTypes = {
]),
options: PropTypes.object,
showTime: PropTypes.bool,
showDate: PropTypes.bool,
};

DateField.displayName = 'DateField';
Expand All @@ -114,6 +130,7 @@ export interface DateFieldProps
locales?: string | string[];
options?: object;
showTime?: boolean;
showDate?: boolean;
}

const toLocaleStringSupportsLocales = (() => {
Expand Down

0 comments on commit 0f79261

Please sign in to comment.