diff --git a/src/lib/core/datetime/native-date-adapter.spec.ts b/src/lib/core/datetime/native-date-adapter.spec.ts index fcde1c3bcea0..7100771f7aba 100644 --- a/src/lib/core/datetime/native-date-adapter.spec.ts +++ b/src/lib/core/datetime/native-date-adapter.spec.ts @@ -296,6 +296,14 @@ describe('NativeDateAdapter', () => { new Date(2018, FEB, 1), new Date(2018, JAN, 1), new Date(2019, JAN, 1))) .toEqual(new Date(2018, FEB, 1)); }); + + it('should use UTC for formatting by default', () => { + if (SUPPORTS_INTL) { + expect(adapter.format(new Date(1800, 7, 14), {day: 'numeric'})).toBe('14'); + } else { + expect(adapter.format(new Date(1800, 7, 14), {day: 'numeric'})).toBe('Thu Aug 14 1800'); + } + }); }); diff --git a/src/lib/core/datetime/native-date-adapter.ts b/src/lib/core/datetime/native-date-adapter.ts index e6d27bc418ac..2269942d050e 100644 --- a/src/lib/core/datetime/native-date-adapter.ts +++ b/src/lib/core/datetime/native-date-adapter.ts @@ -8,6 +8,7 @@ import {Inject, Injectable, Optional, LOCALE_ID} from '@angular/core'; import {DateAdapter} from './date-adapter'; +import {extendObject} from '../util/object-extend'; // TODO(mmalerba): Remove when we no longer support safari 9. @@ -56,6 +57,14 @@ export class NativeDateAdapter extends DateAdapter { super.setLocale(localeId); } + /** + * Whether to use `timeZone: 'utc'` with `Intl.DateTimeFormat` when formatting dates. + * Without this `Intl.DateTimeFormat` sometimes chooses the wrong timeZone, which can throw off + * the result. (e.g. in the en-US locale `new Date(1800, 7, 14).toLocaleDateString()` + * will produce `'8/13/1800'`. + */ + useUtcForDisplay = true; + getYear(date: Date): number { return date.getFullYear(); } @@ -154,6 +163,12 @@ export class NativeDateAdapter extends DateAdapter { format(date: Date, displayFormat: Object): string { if (SUPPORTS_INTL_API) { + if (this.useUtcForDisplay) { + date = new Date(Date.UTC( + date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), + date.getMinutes(), date.getSeconds(), date.getMilliseconds())); + displayFormat = extendObject({}, displayFormat, {timeZone: 'utc'}); + } let dtf = new Intl.DateTimeFormat(this.locale, displayFormat); return this._stripDirectionalityCharacters(dtf.format(date)); }