Skip to content

fix(material-date-fns-adapter): locale not passed into parse function #23653

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 1 commit into from
Oct 12, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import {TestBed, waitForAsync} from '@angular/core/testing';
import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core';
import {Locale} from 'date-fns';
import {ja, enUS, da} from 'date-fns/locale';
import {ja, enUS, da, de} from 'date-fns/locale';
import {DateFnsModule} from './index';

const JAN = 0, FEB = 1, MAR = 2, DEC = 11;
Expand Down Expand Up @@ -175,6 +175,11 @@ describe('DateFnsAdapter', () => {
expect(adapter.parse('', 'MM/dd/yyyy')).toBeNull();
});

it('should parse based on the specified locale', () => {
adapter.setLocale(de);
expect(adapter.parse('02.01.2017', 'P')).toEqual(new Date(2017, JAN, 2));
});

it('should parse invalid value as invalid', () => {
let d = adapter.parse('hello', 'MM/dd/yyyy');
expect(d).not.toBeNull();
Expand Down
4 changes: 2 additions & 2 deletions src/material-date-fns-adapter/adapter/date-fns-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const DAY_OF_WEEK_FORMATS = {
export class DateFnsAdapter extends DateAdapter<Date, Locale> {
constructor(@Optional() @Inject(MAT_DATE_LOCALE) matDateLocale: {}) {
super();
super.setLocale(matDateLocale);
this.setLocale(matDateLocale);
Copy link
Member Author

Choose a reason for hiding this comment

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

This change isn't part of the fix, but I figured that it's less error-prone if we were to add a setLocale override.

}

getYear(date: Date): number {
Expand Down Expand Up @@ -165,7 +165,7 @@ export class DateFnsAdapter extends DateAdapter<Date, Locale> {
}

for (const currentFormat of formats) {
const fromFormat = parse(value, currentFormat, new Date());
const fromFormat = parse(value, currentFormat, new Date(), {locale: this.locale});

if (this.isValid(fromFormat)) {
return fromFormat;
Expand Down