Skip to content

Commit b3f1fb3

Browse files
authored
fix(material/datepicker): fix handling of short years (#20709)
1 parent 4152aec commit b3f1fb3

File tree

2 files changed

+13
-19
lines changed

2 files changed

+13
-19
lines changed

src/material/core/datetime/native-date-adapter.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ describe('NativeDateAdapter', () => {
152152
expect(adapter.getYearName(new Date(2017, JAN, 1))).toBe('2017');
153153
});
154154

155-
it('should year name for low year numbers', () => {
155+
it('should get year name for low year numbers', () => {
156156
const createAndFormat = (year: number) => {
157157
return adapter.getYearName(adapter.createDate(year, JAN, 1));
158158
};

src/material/core/datetime/native-date-adapter.ts

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,12 @@ export class NativeDateAdapter extends DateAdapter<Date> {
283283

284284
/** Creates a date but allows the month and date to overflow. */
285285
private _createDateWithOverflow(year: number, month: number, date: number) {
286-
return this._correctYear(new Date(year, month, date), year);
286+
// Passing the year to the constructor causes year numbers <100 to be converted to 19xx.
287+
// To work around this we use `setFullYear` and `setHours` instead.
288+
const d = new Date();
289+
d.setFullYear(year, month, date);
290+
d.setHours(0, 0, 0, 0);
291+
return d;
287292
}
288293

289294
/**
@@ -318,22 +323,11 @@ export class NativeDateAdapter extends DateAdapter<Date> {
318323
* @returns A Date object with its UTC representation based on the passed in date info
319324
*/
320325
private _format(dtf: Intl.DateTimeFormat, date: Date) {
321-
const year = date.getFullYear();
322-
const d = new Date(Date.UTC(
323-
year, date.getMonth(), date.getDate(), date.getHours(),
324-
date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
325-
return dtf.format(this._correctYear(d, year));
326-
}
327-
328-
/**
329-
* Corrects the year of a date, accounting for the fact that JS
330-
* native Date treats years between 0 and 99 as abbreviations for 19xx.
331-
*/
332-
private _correctYear(date: Date, intendedYear: number): Date {
333-
if (intendedYear >= 0 && intendedYear < 100) {
334-
date.setFullYear(this.getYear(date) - 1900);
335-
}
336-
337-
return date;
326+
// Passing the year to the constructor causes year numbers <100 to be converted to 19xx.
327+
// To work around this we use `setUTCFullYear` and `setUTCHours` instead.
328+
const d = new Date();
329+
d.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());
330+
d.setUTCHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
331+
return dtf.format(d);
338332
}
339333
}

0 commit comments

Comments
 (0)