fix(common): parse YYYY strings as UTC dates (#40629)

In b6cd38ff055f003f92fff4c3e27d165fb4437057 we fixed the DatePipe so
that when it parsed date strings that looked like `YYYY-MM` it created a UTC
date that was not affected by the local timezone of the JavaScript engine.

This commit does the same for date strings of the form `YYYY`.

(Note that the previous commit, mentioned above, attempted to fix this case
too but the test was not actually checking the correct input string.)

Fixes #33944

PR Close #40620

PR Close #40629
This commit is contained in:
Pete Bacon Darwin 2021-01-29 11:35:52 +00:00 committed by Misko Hevery
parent b6cd38ff05
commit ca0f6e6eed
2 changed files with 8 additions and 8 deletions

View File

@ -711,13 +711,6 @@ export function toDate(value: string|number|Date): Date {
if (typeof value === 'string') { if (typeof value === 'string') {
value = value.trim(); value = value.trim();
const parsedNb = parseFloat(value);
// any string that only contains numbers, like "1234" but not like "1234hello"
if (!isNaN(value as any - parsedNb)) {
return new Date(parsedNb);
}
if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) { if (/^(\d{4}(-\d{1,2}(-\d{1,2})?)?)$/.test(value)) {
/* For ISO Strings without time the day, month and year must be extracted from the ISO String /* For ISO Strings without time the day, month and year must be extracted from the ISO String
before Date creation to avoid time offset and errors in the new Date. before Date creation to avoid time offset and errors in the new Date.
@ -730,6 +723,13 @@ export function toDate(value: string|number|Date): Date {
return new Date(y, m - 1, d); return new Date(y, m - 1, d);
} }
const parsedNb = parseFloat(value);
// any string that only contains numbers, like "1234" but not like "1234hello"
if (!isNaN(value as any - parsedNb)) {
return new Date(parsedNb);
}
let match: RegExpMatchArray|null; let match: RegExpMatchArray|null;
if (match = value.match(ISO8601_DATE_REGEX)) { if (match = value.match(ISO8601_DATE_REGEX)) {
return isoStringToDate(match); return isoStringToDate(match);

View File

@ -61,7 +61,7 @@ describe('Format date', () => {
describe('formatDate', () => { describe('formatDate', () => {
const isoStringWithoutTime = '2015-01-01'; const isoStringWithoutTime = '2015-01-01';
const isoStringWithoutTimeOrDate = '2015-01'; const isoStringWithoutTimeOrDate = '2015-01';
const isoStringWithoutTimeOrDateOrMonth = '2015-01'; const isoStringWithoutTimeOrDateOrMonth = '2015';
const defaultFormat = 'mediumDate'; const defaultFormat = 'mediumDate';
let date: Date; let date: Date;