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

Fix DateField show wrong date on negative time zones #7242

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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