Skip to content

Commit fd8ef16

Browse files
authored
Merge pull request #7242 from marmelab/fix-5578
Fix DateField show wrong date on negative time zones
2 parents a7d54ed + 3c5aa28 commit fd8ef16

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

packages/ra-ui-materialui/src/field/DateField.spec.tsx

+13
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,19 @@ describe('<DateField />', () => {
3131
expect(queryByText(date)).not.toBeNull();
3232
});
3333

34+
it('should render a date string', () => {
35+
const { queryByText } = render(
36+
<DateField
37+
record={{ id: 123, foo: '2017-04-23' }}
38+
source="foo"
39+
locales="en-US"
40+
/>
41+
);
42+
43+
const date = new Date('2017-04-23').toLocaleDateString('en-US');
44+
expect(queryByText(date)).not.toBeNull();
45+
});
46+
3447
it('should use record from RecordContext', () => {
3548
const { queryByText } = render(
3649
<RecordContextProvider

packages/ra-ui-materialui/src/field/DateField.tsx

+13-1
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,24 @@ export const DateField: FC<DateFieldProps> = memo(props => {
7171
}
7272

7373
const date = value instanceof Date ? value : new Date(value);
74+
let dateOptions = options;
75+
if (
76+
typeof value === 'string' &&
77+
value.length <= 10 &&
78+
!showTime &&
79+
!options
80+
) {
81+
// Input is a date string (e.g. '2022-02-15') without time and time zone.
82+
// Force timezone to UTC to fix issue with people in negative time zones
83+
// who may see a different date when calling toLocaleDateString().
84+
dateOptions = { timeZone: 'UTC' };
85+
}
7486
const dateString = showTime
7587
? toLocaleStringSupportsLocales
7688
? date.toLocaleString(locales, options)
7789
: date.toLocaleString()
7890
: toLocaleStringSupportsLocales
79-
? date.toLocaleDateString(locales, options)
91+
? date.toLocaleDateString(locales, dateOptions)
8092
: date.toLocaleDateString();
8193

8294
return (

0 commit comments

Comments
 (0)