diff --git a/packages/ra-ui-materialui/src/field/DateField.spec.tsx b/packages/ra-ui-materialui/src/field/DateField.spec.tsx index ceadcf3aaa2..f67e524c30b 100644 --- a/packages/ra-ui-materialui/src/field/DateField.spec.tsx +++ b/packages/ra-ui-materialui/src/field/DateField.spec.tsx @@ -71,6 +71,21 @@ describe('', () => { expect(queryByText(date)).not.toBeNull(); }); + it('should render only a time when the showtime prop is true and showdate is false', () => { + const { queryByText } = render( + + ); + + 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 = { diff --git a/packages/ra-ui-materialui/src/field/DateField.tsx b/packages/ra-ui-materialui/src/field/DateField.tsx index 3c5ab3a661e..4f523290fc6 100644 --- a/packages/ra-ui-materialui/src/field/DateField.tsx +++ b/packages/ra-ui-materialui/src/field/DateField.tsx @@ -39,9 +39,17 @@ export const DateField: FC = memo(props => { locales, options, showTime = false, + showDate = true, source, ...rest } = props; + + if (!showTime && !showDate) { + throw new Error( + ' cannot have showTime and showDate false at the same time' + ); + } + const record = useRecordContext(props); if (!record) { return null; @@ -73,13 +81,20 @@ export const DateField: FC = 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 ( {