From ca0f6e6eed3fdf79e2a4344fc1d6abc99dfc2d01 Mon Sep 17 00:00:00 2001 From: Pete Bacon Darwin Date: Fri, 29 Jan 2021 11:35:52 +0000 Subject: [PATCH] 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 --- packages/common/src/i18n/format_date.ts | 14 +++++++------- packages/common/test/i18n/format_date_spec.ts | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/common/src/i18n/format_date.ts b/packages/common/src/i18n/format_date.ts index acb24f99ca..ebeefaedb5 100644 --- a/packages/common/src/i18n/format_date.ts +++ b/packages/common/src/i18n/format_date.ts @@ -711,13 +711,6 @@ export function toDate(value: string|number|Date): Date { if (typeof value === 'string') { 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)) { /* 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. @@ -730,6 +723,13 @@ export function toDate(value: string|number|Date): Date { 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; if (match = value.match(ISO8601_DATE_REGEX)) { return isoStringToDate(match); diff --git a/packages/common/test/i18n/format_date_spec.ts b/packages/common/test/i18n/format_date_spec.ts index fe4dbb83b6..a08ce87ddc 100644 --- a/packages/common/test/i18n/format_date_spec.ts +++ b/packages/common/test/i18n/format_date_spec.ts @@ -61,7 +61,7 @@ describe('Format date', () => { describe('formatDate', () => { const isoStringWithoutTime = '2015-01-01'; const isoStringWithoutTimeOrDate = '2015-01'; - const isoStringWithoutTimeOrDateOrMonth = '2015-01'; + const isoStringWithoutTimeOrDateOrMonth = '2015'; const defaultFormat = 'mediumDate'; let date: Date;