Skip to content

Commit

Permalink
fix(moment-adapter): incorrectly deserializing moment dates and not s…
Browse files Browse the repository at this point in the history
…etting locale on deserialized values (#14685)

Fixes a couple of issues I noticed while doing the Luxon adapter:
* If a `Moment` instance was passed in to `deserialize`, we were returning a new `Moment` instance set to the current date/time, rather than the ones from the passed-in object.
* In some cases the object returned by `deserialize` didn't have its locale set to the one from the adapter.
  • Loading branch information
crisbeto authored and mmalerba committed Jan 3, 2019
1 parent 65d615b commit 36db1c0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
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

0 comments on commit 36db1c0

Please sign in to comment.