Skip to content

fix(moment-adapter): incorrectly deserializing moment dates and not setting locale on deserialized values #14685

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/material-moment-adapter/adapter/moment-date-adapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,19 @@ describe('MomentDateAdapter', () => {
assertValidDate(adapter.deserialize(moment.invalid()), false);
});

it('should clone the date when deserializing a Moment date', () => {
let date = moment([2017, JAN, 1]);
expect(adapter.deserialize(date)!.format()).toEqual(date.format());
expect(adapter.deserialize(date)).not.toBe(date);
});

it('should deserialize dates with the correct locale', () => {
adapter.setLocale('ja');
expect(adapter.deserialize('1985-04-12T23:20:50.52Z')!.locale()).toBe('ja');
expect(adapter.deserialize(new Date())!.locale()).toBe('ja');
expect(adapter.deserialize(moment())!.locale()).toBe('ja');
});

it('setLocale should not modify global moment locale', () => {
expect(moment.locale()).toBe('en');
adapter.setLocale('ja-JP');
Expand Down
7 changes: 5 additions & 2 deletions src/material-moment-adapter/adapter/moment-date-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,10 @@ export class MomentDateAdapter extends DateAdapter<Moment> {
deserialize(value: any): Moment | null {
let date;
if (value instanceof Date) {
date = this._createMoment(value);
date = this._createMoment(value).locale(this.locale);
} else if (this.isDateInstance(value)) {
// Note: assumes that cloning also sets the correct locale.
return this.clone(value);
}
if (typeof value === 'string') {
if (!value) {
Expand All @@ -220,7 +223,7 @@ export class MomentDateAdapter extends DateAdapter<Moment> {
date = this._createMoment(value, moment.ISO_8601).locale(this.locale);
}
if (date && this.isValid(date)) {
return date;
return this._createMoment(date).locale(this.locale);
}
return super.deserialize(value);
}
Expand Down