I want to display Date using European format dd/MM/yyyy
but using DatePipe shortDate format it only display using US date style MM/dd/yyyy
.
I'm assuming thats the default locale is en_US. Maybe I am missing in the docs but how can I change the default locale settings in an Angular2 app? Or maybe is there some way to pass a custom format to DatePipe ?
The date pipe uses the LOCALE_ID to determine the default locale to use. By default, LOCALE_ID is set to en-US . We can change the app locale by LOCALE_ID setting in the AppModule .
Angular Date Pipe allows us to format dates in Angular using the requested format, time zone & local information. It comes with built-in pre-defined formats. We can also customize the date format by creating custom format strings. We can set the time zone, country locale, etc.
As of Angular2 RC6, you can set default locale in your app module, by adding a provider:
@NgModule({ providers: [ { provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale //otherProviders... ] })
The Currency/Date/Number pipes should pick up the locale. LOCALE_ID is an OpaqueToken, to be imported from angular/core.
import { LOCALE_ID } from '@angular/core';
For a more advanced use case, you may want to pick up locale from a service. Locale will be resolved (once) when component using date pipe is created:
{ provide: LOCALE_ID, deps: [SettingsService], //some service handling global settings useFactory: (settingsService) => settingsService.getLanguage() //returns locale string }
Hope it works for you.
Solution with LOCALE_ID is great if you want to set the language for your app once. But it doesn’t work, if you want to change the language during runtime. For this case you can implement custom date pipe.
import { DatePipe } from '@angular/common'; import { Pipe, PipeTransform } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Pipe({ name: 'localizedDate', pure: false }) export class LocalizedDatePipe implements PipeTransform { constructor(private translateService: TranslateService) { } transform(value: any, pattern: string = 'mediumDate'): any { const datePipe: DatePipe = new DatePipe(this.translateService.currentLang); return datePipe.transform(value, pattern); } }
Now if you change the app display language using TranslateService (see ngx-translate)
this.translateService.use('en');
the formats within your app should automatically being updated.
Example of use:
<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p> <p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>
or check my simple "Notes" project here.
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