Skip to content

Commit 76cc6f0

Browse files
mmalerbaandrewseguin
authored andcommitted
fix(datepicker): force Intl.DateTimeFormat to use UTC time zone ... (#5747)
* fix(datepicker): force Intl.DateTimeFormat to use UTC time zone so it doesn't display incorrect dates. * fix lint and test * don't use Object.assign
1 parent f06fe11 commit 76cc6f0

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,14 @@ describe('NativeDateAdapter', () => {
296296
new Date(2018, FEB, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1)))
297297
.toEqual(new Date(2018, FEB, 1));
298298
});
299+
300+
it('should use UTC for formatting by default', () => {
301+
if (SUPPORTS_INTL) {
302+
expect(adapter.format(new Date(1800, 7, 14), {day: 'numeric'})).toBe('14');
303+
} else {
304+
expect(adapter.format(new Date(1800, 7, 14), {day: 'numeric'})).toBe('Thu Aug 14 1800');
305+
}
306+
});
299307
});
300308

301309

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import {Inject, Injectable, Optional, LOCALE_ID} from '@angular/core';
1010
import {DateAdapter} from './date-adapter';
11+
import {extendObject} from '../util/object-extend';
1112

1213

1314
// TODO(mmalerba): Remove when we no longer support safari 9.
@@ -56,6 +57,14 @@ export class NativeDateAdapter extends DateAdapter<Date> {
5657
super.setLocale(localeId);
5758
}
5859

60+
/**
61+
* Whether to use `timeZone: 'utc'` with `Intl.DateTimeFormat` when formatting dates.
62+
* Without this `Intl.DateTimeFormat` sometimes chooses the wrong timeZone, which can throw off
63+
* the result. (e.g. in the en-US locale `new Date(1800, 7, 14).toLocaleDateString()`
64+
* will produce `'8/13/1800'`.
65+
*/
66+
useUtcForDisplay = true;
67+
5968
getYear(date: Date): number {
6069
return date.getFullYear();
6170
}
@@ -154,6 +163,12 @@ export class NativeDateAdapter extends DateAdapter<Date> {
154163

155164
format(date: Date, displayFormat: Object): string {
156165
if (SUPPORTS_INTL_API) {
166+
if (this.useUtcForDisplay) {
167+
date = new Date(Date.UTC(
168+
date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(),
169+
date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
170+
displayFormat = extendObject({}, displayFormat, {timeZone: 'utc'});
171+
}
157172
let dtf = new Intl.DateTimeFormat(this.locale, displayFormat);
158173
return this._stripDirectionalityCharacters(dtf.format(date));
159174
}

0 commit comments

Comments
 (0)