From 97c6f6e95c6fc95f262b1aac8628266d717315c3 Mon Sep 17 00:00:00 2001 From: crisbeto Date: Mon, 31 Dec 2018 09:25:16 +0200 Subject: [PATCH] fix(moment-adapter): incorrectly deserializing moment dates and not setting locale on deserialized values 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. --- .../adapter/moment-date-adapter.spec.ts | 13 +++++++++++++ .../adapter/moment-date-adapter.ts | 7 +++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts index 41b5860e9383..10548e902f5d 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts @@ -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'); diff --git a/src/material-moment-adapter/adapter/moment-date-adapter.ts b/src/material-moment-adapter/adapter/moment-date-adapter.ts index 32fc0b2b8f1b..ea05ecb63f76 100644 --- a/src/material-moment-adapter/adapter/moment-date-adapter.ts +++ b/src/material-moment-adapter/adapter/moment-date-adapter.ts @@ -211,7 +211,10 @@ export class MomentDateAdapter extends DateAdapter { 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) { @@ -220,7 +223,7 @@ export class MomentDateAdapter extends DateAdapter { 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); }