How to Change language of Datepicker of Material Angular? I can't find in documentation for Angular material 2. Here is a plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview
<md-input-container> <input mdInput [mdDatepicker]="picker" placeholder="Choose a date"> <button mdSuffix [mdDatepickerToggle]="picker"></button> </md-input-container> <md-datepicker #picker></md-datepicker>
Angular material provides MAT_DATE_LOCALE whose value can be overridden in application module to change the default locale. To change locale at run time, we need to use setLocale method of DateAdapter . On this page we will provide complete example to set locale such as fr-FR, en-US and hi-IN for our Datepicker.
The Angular Time Picker, also known as the Angular Material Time Picker is a lightweight and mobile-friendly component that allows end users to select a time value either from a pop-up time list or by entering the value directly in the text box.
import {MAT_DATE_LOCALE} from '@angular/material';
&
providers: [{ provide: MAT_DATE_LOCALE, useValue: 'es-ES' }]
Do this in tpv.modules.ts
md-datepicker provides setLocale
method which can be used to set any language (list of locale).
Here's an example of setting locale to 'fr':
export class DatepickerOverviewExample { constructor(private dateAdapter: DateAdapter<Date>) { this.dateAdapter.setLocale('fr'); } }
One thing to keep in mind, md-datepicker's default date parsing format is mm/dd/yyyy
, so if a locale has a different date format (for 'fr' its dd/mm/yyyy
), we will need to define a class that extends NativeDateAdapter
to parse the new date format. Without setting the proper date format, there will be an issue like this question.
import { NativeDateAdapter, DateAdapter, MD_DATE_FORMATS } from "@angular/material/core"; export class FrenchDateAdapter extends NativeDateAdapter { parse(value: any): Date | null { if ((typeof value === 'string') && (value.indexOf('/') > -1)) { const str = value.split('/'); if (str.length < 2 || isNaN(+str[0]) || isNaN(+str[1]) || isNaN(+str[2])) { return null; } return new Date(Number(str[2]), Number(str[1]) - 1, Number(str[0]), 12); } const timestamp = typeof value === 'number' ? value : Date.parse(value); return isNaN(timestamp) ? null : new Date(timestamp); } } @Component({ ... providers: [{provide: DateAdapter, useClass: FrenchDateAdapter}], })
Plunker demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With