Skip to content

Commit 36db1c0

Browse files
crisbetommalerba
authored andcommittedJan 3, 2019
fix(moment-adapter): incorrectly deserializing moment dates and not setting 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.
1 parent 65d615b commit 36db1c0

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed
 

‎src/material-moment-adapter/adapter/moment-date-adapter.spec.ts

+13
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,19 @@ describe('MomentDateAdapter', () => {
333333
assertValidDate(adapter.deserialize(moment.invalid()), false);
334334
});
335335

336+
it('should clone the date when deserializing a Moment date', () => {
337+
let date = moment([2017, JAN, 1]);
338+
expect(adapter.deserialize(date)!.format()).toEqual(date.format());
339+
expect(adapter.deserialize(date)).not.toBe(date);
340+
});
341+
342+
it('should deserialize dates with the correct locale', () => {
343+
adapter.setLocale('ja');
344+
expect(adapter.deserialize('1985-04-12T23:20:50.52Z')!.locale()).toBe('ja');
345+
expect(adapter.deserialize(new Date())!.locale()).toBe('ja');
346+
expect(adapter.deserialize(moment())!.locale()).toBe('ja');
347+
});
348+
336349
it('setLocale should not modify global moment locale', () => {
337350
expect(moment.locale()).toBe('en');
338351
adapter.setLocale('ja-JP');

‎src/material-moment-adapter/adapter/moment-date-adapter.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,10 @@ export class MomentDateAdapter extends DateAdapter<Moment> {
211211
deserialize(value: any): Moment | null {
212212
let date;
213213
if (value instanceof Date) {
214-
date = this._createMoment(value);
214+
date = this._createMoment(value).locale(this.locale);
215+
} else if (this.isDateInstance(value)) {
216+
// Note: assumes that cloning also sets the correct locale.
217+
return this.clone(value);
215218
}
216219
if (typeof value === 'string') {
217220
if (!value) {
@@ -220,7 +223,7 @@ export class MomentDateAdapter extends DateAdapter<Moment> {
220223
date = this._createMoment(value, moment.ISO_8601).locale(this.locale);
221224
}
222225
if (date && this.isValid(date)) {
223-
return date;
226+
return this._createMoment(date).locale(this.locale);
224227
}
225228
return super.deserialize(value);
226229
}

0 commit comments

Comments
 (0)
Please sign in to comment.