diff --git a/src/material/core/datetime/native-date-adapter.spec.ts b/src/material/core/datetime/native-date-adapter.spec.ts index 3566231edf79..194432816bc2 100644 --- a/src/material/core/datetime/native-date-adapter.spec.ts +++ b/src/material/core/datetime/native-date-adapter.spec.ts @@ -152,7 +152,7 @@ describe('NativeDateAdapter', () => { expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017'); }); - it('should year name for low year numbers', () => { + it('should get year name for low year numbers', () => { const createAndFormat = (year: number) => { return adapter.getYearName(adapter.createDate(year, JAN, 1)); }; diff --git a/src/material/core/datetime/native-date-adapter.ts b/src/material/core/datetime/native-date-adapter.ts index 6e2d1cccd1e3..e4026e47be4d 100644 --- a/src/material/core/datetime/native-date-adapter.ts +++ b/src/material/core/datetime/native-date-adapter.ts @@ -283,7 +283,12 @@ export class NativeDateAdapter extends DateAdapter { /** Creates a date but allows the month and date to overflow. */ private _createDateWithOverflow(year: number, month: number, date: number) { - return this._correctYear(new Date(year, month, date), year); + // Passing the year to the constructor causes year numbers <100 to be converted to 19xx. + // To work around this we use `setFullYear` and `setHours` instead. + const d = new Date(); + d.setFullYear(year, month, date); + d.setHours(0, 0, 0, 0); + return d; } /** @@ -318,22 +323,11 @@ export class NativeDateAdapter extends DateAdapter { * @returns A Date object with its UTC representation based on the passed in date info */ private _format(dtf: Intl.DateTimeFormat, date: Date) { - const year = date.getFullYear(); - const d = new Date(Date.UTC( - year, date.getMonth(), date.getDate(), date.getHours(), - date.getMinutes(), date.getSeconds(), date.getMilliseconds())); - return dtf.format(this._correctYear(d, year)); - } - - /** - * Corrects the year of a date, accounting for the fact that JS - * native Date treats years between 0 and 99 as abbreviations for 19xx. - */ - private _correctYear(date: Date, intendedYear: number): Date { - if (intendedYear >= 0 && intendedYear < 100) { - date.setFullYear(this.getYear(date) - 1900); - } - - return date; + // Passing the year to the constructor causes year numbers <100 to be converted to 19xx. + // To work around this we use `setUTCFullYear` and `setUTCHours` instead. + const d = new Date(); + d.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + d.setUTCHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()); + return dtf.format(d); } }