Skip to content

Commit

Permalink
Merge pull request #7242 from marmelab/fix-5578
Browse files Browse the repository at this point in the history
Fix DateField show wrong date on negative time zones
  • Loading branch information
djhi committed Feb 15, 2022
2 parents a7d54ed + 3c5aa28 commit fd8ef16
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
13 changes: 13 additions & 0 deletions packages/ra-ui-materialui/src/field/DateField.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ describe('<DateField />', () => {
expect(queryByText(date)).not.toBeNull();
});

it('should render a date string', () => {
const { queryByText } = render(
<DateField
record={{ id: 123, foo: '2017-04-23' }}
source="foo"
locales="en-US"
/>
);

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

it('should use record from RecordContext', () => {
const { queryByText } = render(
<RecordContextProvider
Expand Down
14 changes: 13 additions & 1 deletion packages/ra-ui-materialui/src/field/DateField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,24 @@ export const DateField: FC<DateFieldProps> = memo(props => {
}

const date = value instanceof Date ? value : new Date(value);
let dateOptions = options;
if (
typeof value === 'string' &&
value.length <= 10 &&
!showTime &&
!options
) {
// Input is a date string (e.g. '2022-02-15') without time and time zone.
// Force timezone to UTC to fix issue with people in negative time zones
// who may see a different date when calling toLocaleDateString().
dateOptions = { timeZone: 'UTC' };
}
const dateString = showTime
? toLocaleStringSupportsLocales
? date.toLocaleString(locales, options)
: date.toLocaleString()
: toLocaleStringSupportsLocales
? date.toLocaleDateString(locales, options)
? date.toLocaleDateString(locales, dateOptions)
: date.toLocaleDateString();

return (
Expand Down

0 comments on commit fd8ef16

Please sign in to comment.