Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(datepicker): force Intl.DateTimeFormat to use UTC time zone ... #5747

Merged
merged 3 commits into from
Jul 25, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/lib/core/datetime/native-date-adapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
expect(adapter.format(new Date(1800, 7, 14), {day: 'numeric'})).toBe('14');

adapter.useUtcForDisplay = false;

expect(adapter.format(new Date(1800, 7, 14), {day: 'numeric'})).toBe('13');
})
});


Expand Down
14 changes: 14 additions & 0 deletions src/lib/core/datetime/native-date-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ export class NativeDateAdapter extends DateAdapter<Date> {
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();
}
Expand Down Expand Up @@ -154,6 +162,12 @@ export class NativeDateAdapter extends DateAdapter<Date> {

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 = Object.assign({}, displayFormat, {timeZone: 'utc'});
Copy link
Contributor

@kara kara Jul 19, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mmalerba Object.assign is breaking in Google. Can you switch to our util extendObject?

}
let dtf = new Intl.DateTimeFormat(this.locale, displayFormat);
return this._stripDirectionalityCharacters(dtf.format(date));
}
Expand Down