Handle ambiguous dates (with no offset) in DateTimePickerControl (#35077)

* Add tests for ambiguous and unambiguous UTC dates

* Assume UTC for ambiguous dates

* Changelog

* Remove console statements
This commit is contained in:
Matt Sherman 2022-10-14 15:38:18 -04:00 committed by GitHub
parent 1eecefb715
commit 0cbc45ba85
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 58 additions and 5 deletions

View File

@ -0,0 +1,4 @@
Significance: patch
Type: tweak
Assume ambiguous dates passed into DateTimePickerControl are UTC.

View File

@ -75,20 +75,28 @@ export const DateTimePickerControl: React.FC< DateTimePickerControlProps > = ( {
null
);
function parseMomentIso( dateString?: string | null ): Moment {
return moment( dateString, moment.ISO_8601, true );
function parseMomentIso(
dateString?: string | null,
assumeLocalTime = false
): Moment {
if ( assumeLocalTime ) {
return moment( dateString, moment.ISO_8601, true ).utc();
}
return moment.utc( dateString, moment.ISO_8601, true );
}
function parseMoment( dateString?: string | null ): Moment {
// parse input date string as local time
return moment( dateString, dateTimeFormat );
}
function formatMomentIso( momentDate: Moment ): string {
return momentDate.toISOString();
return momentDate.utc().toISOString();
}
function formatMoment( momentDate: Moment ): string {
return momentDate.format( dateTimeFormat );
return momentDate.local().format( dateTimeFormat );
}
function hasFocusLeftInputAndDropdownContent(
@ -272,8 +280,9 @@ export const DateTimePickerControl: React.FC< DateTimePickerControlProps > = ( {
: undefined
}
onChange={ ( date: string ) => {
// the picker returns the date in local time
const formattedDate = formatMoment(
parseMomentIso( date )
parseMomentIso( date, true )
);
changeImmediate( formattedDate, true );
} }

View File

@ -106,6 +106,46 @@ describe( 'DateTimePickerControl', () => {
);
} );
it( 'should assume ambiguous dates are UTC', () => {
const ambiguousISODateTimeString = '2202-09-15T22:30:40';
const { container } = render(
<DateTimePickerControl
currentDate={ ambiguousISODateTimeString }
is12Hour={ false }
/>
);
const input = container.querySelector( 'input' );
expect( input?.value ).toBe(
moment
.utc( ambiguousISODateTimeString )
.local()
.format( default24HourDateTimeFormat )
);
} );
it( 'should handle unambiguous UTC dates', () => {
const unambiguousISODateTimeString = '2202-09-15T22:30:40Z';
const { container } = render(
<DateTimePickerControl
currentDate={ unambiguousISODateTimeString }
is12Hour={ false }
/>
);
const input = container.querySelector( 'input' );
expect( input?.value ).toBe(
moment
.utc( unambiguousISODateTimeString )
.local()
.format( default24HourDateTimeFormat )
);
} );
it( 'should use the default 12 hour date time format', () => {
const dateTime = moment( '2022-09-15 02:30:40' );