Angular: How to display a date in French format
Asked Answered
S

5

12

I am an Angular beginner, I read the documentation of Angular, and it's hard for such an elementary thing... I want that the dates and other things in my application have the French locale, and not the default 'en-US'...

I started to read this Angular documentation, that seems a little bit incomplete, cause, I did the doc states, and failed:

>...\ClientApp>ng serve --configuration=fr
Configuration 'fr' could not be found in project 'ClientApp'.

OK, now I look on another documentation page on the Date pipe. It states:

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}

but ANY example on how to use the locale, so, I tried to do it in a test application link, like this {{myDate | date: 'medium': undefined : 'fr'}} but it displays nothing... I have in the console:

ERROR
Error: InvalidPipeArgument: 'Missing locale data for the locale "fr".' for pipe 'DatePipe'

what else should I do or install to display in Angular a date in the French format?

Angular CLI: 6.1.5
Node: 8.11.1
OS: win32 x64
Angular: 6.1.8
Saladin answered 21/9, 2018 at 8:56 Comment(0)
G
27

Try adding to your app module the following code

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

// the second parameter 'fr' is optional
registerLocaleData(localeFr, 'fr');

https://angular.io/guide/i18n#i18n-pipes

EDIT: Then if you want to sets this locale as default you need to set the LOCALE_ID injection token as 'fr' like that :

{provide: LOCALE_ID, useValue: 'fr' }

In your app module

Hope it helps

Gunyah answered 21/9, 2018 at 9:13 Comment(20)
Does not find the fr module, I tried here stackblitz.com/edit/angular-gitter-vjjuasSaladin
I saw, but in local, how about the ng serve, what is wrong with it? should I serve it in "fr" or serve as usually ng serve -o?Saladin
and, just, have a look on the component html I put {{myDate | date: 'medium'}} and it turns back to English, I want all my application to be in French without explicit set on every parameterSaladin
It depends on how you want to internationalize you app. if you use the github.com/ngx-translate/core library, you won't need to serve it in fr. If you keep the i18n process in the angular doc, you will need to serve it as frGunyah
actually I don't want to internationalize the application. I just want my dates and numbers be in French format, it's all I needSaladin
If you want just fr date and number by default, you can "trick" the internationalization process by setting the 'en' key to the fr locale : registerLocaleData(localeFr, 'en'); Then all you pipes will use by default the fr locale.Gunyah
is not the case in this sample, i modified the main.ts: stackblitz.com/edit/angular-gitter-jcxhumSaladin
Fixed it : stackblitz.com/edit/angular-gitter-ztcyiw If you register the frLocale as 'en' this will be the defaultGunyah
I don't see any logic... to register the "fr" locale as "en" and then see the result in French...?!Saladin
Yes, the 'en' key is the default in angular, you just switch the reference to the fr locale. The 'en' value is nothing but a key, this doesn't mean anything, you can call it 'jvqdjvqjvdhqvhzd' if you want and use it inside a pipe.Gunyah
I switch from default en to explicit fr, the documentation tells me I should put registerLocaleData(localeFr, 'fr');, so, if I can put 'jvqdjvqjvdhqvhzd', why the 'fr' doesn't work, but 'en' works?Saladin
By invoking registerLocaleData(localeFr, 'fr') you create a link between the string fr and the locale localeFr, and you can then use it in pipes like that {{myDate | date: 'fr'}}, if you register registerLocaleData(localeFr, 'toto') The result of {{myDate | date: 'toto'}} will be the same. The trick is that the default value of the locale key is en so if you invoke registerLocaleData(localeFr, 'en') the en key will no longer lead to the localeEn but the localeFr value will be usedGunyah
its strange for me, why would I put "toto" instead of "fr", and why should I link the 'fr' to the locale "fr", for me it should already be linked by angular, and I don't really rely on pipes explicit format, I need rather just to use "fr" as primary implicit language in the whole application, so "date" filter immediately and without additional precision convert my date to the french format...Saladin
<<the default value is "en" so if you invoke registerLocaleData(localeFr, 'en') the "en" key will no longer lead to the locale>> here my brain explodes....Saladin
when I register locale("en"), the "en" will not be registered any longer as locale.... what kind of pervert inverted logic is that?Saladin
You don't have to, the fr string is optional. There is an injection token somewhere that sets the default somewhereGunyah
I don't have to? without registerLocaleData(localeFr, 'en'); nothing worked as expected... if this shit is optional, why should we talk about it, and just not to omit it from the code?Saladin
Found out, you have to register the fr locale AND set the LOCALE_ID injection token to 'fr' stackblitz.com/edit/angular-gitter-pa3dyqGunyah
You did not understand, the registerLocaleData(localeFr, 'en'); was a shitty workaround but still a workaround, i've editted my original post with a way proper solution.Gunyah
Hello pierre, you should add "registerLocaleData(localeFr, 'en')" to your answer as an alternative. The only that worked for me! Thanks!Resigned
P
9

The answer depends on the version of angular that you are using. You have to provide for the LOCALE which you will be using.The default LOCALE is configured as en-US and for all others, you have to manually add the same as providers. Only the way of providing for the LOCALES differs in the angular versions. Check the below:

  1. Angular 5 and above:

    Add the following lines in your app.module.ts:

    import { registerLocaleData } from '@angular/common';
    import localeFr from '@angular/common/locales/fr';
    registerLocaleData(localeFr, 'fr');
    
  2. Below Angular 5:

    Add the following lines in your app.module.ts:

    import { LOCALE_ID } from '@angular/core';
    
    @NgModule({
        imports : [],
        providers: [ { provide: LOCALE_ID, useValue: "fr-FR" }]
        //Your code
    })
    
Pamper answered 21/9, 2018 at 9:37 Comment(9)
I have the 6th Angular, but I try to do in the sample from the OP(stackblitz.com/edit/angular-gitter-vjjuas), it says "Cannot find module @angular/common/locales/fr"Saladin
how about the ng serve, what is wrong with it? should I serve it in "fr" or serve as usually ng serve -o?Saladin
and how is supposed the date pipe to work with the locale? {myDate | date: 'short': 'fr'}?Saladin
First of all, the given code works on stackblitz. If you still face a problem, try import { registerLocaleData, localeFr} from '@angular/common'; for the import.Pamper
Secondly, you can use the locale parameter as fr will display dates, percentages, text etc all in the local format. Check - medium.com/frontend-fun/…Pamper
Thirdly, {myDate | date: 'short': 'fr'} should work fine. If you face some problems, you can try github.com/Aaron-Sterling/ng-datefns-pipes/blob/master/src/… Someone has implemented their own version for the angular date pipe.Pamper
I don't need to implement my own, I am beginner, I just need to understand how it works... cause for me date [ : format [ : timezone [ : locale ] ] ] means that I should put a timezone before the "fr"... I don't want to put a timezone, Ijust need my date in FrenchSaladin
I use Angular6, but only when adding both parts of your code (for Angular 5 and 6), the local project started to display the data in FrenchSaladin
Be careful to not mix up fr and fr-FR... ;)Evangelineevangelism
A
4

Simply try this(french format: [Day name] [Day number] [Month name] [Year number])

{{myDate | date:'EEEE, d,MMMM, y'}}

if you dont want day name remove 'EEEE' from pipe

OR

  1. update your module.ts

    import { NgModule, LOCALE_ID } from '@angular/core';

    import { registerLocaleData } from '@angular/common';

    import localeFr from '@angular/common/locales/fr';

    registerLocaleData(localeFr);

    .....

    @NgModule({

    ..... providers: [ {provide: LOCALE_ID, useValue: "fr-CA" } ]

    })

will do the work

Ajani answered 21/9, 2018 at 9:39 Comment(8)
stackblitz.com/edit/angular-gitter-vjjuas, it does not find the fr module, and why should I use fr-CA? )Saladin
simply using the format will not display me the month names in FrenchSaladin
its Java Locale “French (Canada)” (fr-CA)Ajani
I am getting a perfect response : vendredi 21 septembre 2018. @NgModule({ imports: [ providers: [ {provide: LOCALE_ID, useValue: "fr-CA" } })Ajani
problem may be with plunker try it in your local environment. working fine in my angular 6 ApplicationAjani
what the point of the useValue: "fr-CA" if it works under "local environment" in , say, Spanish or Chinese?Saladin
@Serge go through all locale here : science.co.il/language/Locale-codes.phpAjani
your first option {{myDate | date:'EEEE, d,MMMM, y'}} didn't translate anything in french, so irrelevant to the answer. Could you remove it do not confuse people? the second part of the answer is OK, but there's nothing wrong with the plunkerSaladin
W
2

The Internet seems to agree with Jahnavi Paliwal's answer on this point, however I believe we are now supposed to be setting it via angular.json file and FETCHING it (if we need to) via the LOCALE_ID provider. If you do the following then the Date Pipe and Angular Material DatePicker (etc.) will use the correct Locale out of the box without having to manually change LOCALE_ID in your Module definition.

"projects": {
  "myProject": {
    "projectType": "application",
    ...
    },
    "i18n": {
      "sourceLocale": "en-GB" // <-- specify your preferred default
    },
    "architect": {
      "build": {
        ...
        "options": {
          "localize": true, // <-- tell Angular to check
          ...
          "aot": true,
          "outputPath": "dist",
Wilmington answered 3/7, 2020 at 15:22 Comment(1)
This should be the selected answer.Evangelineevangelism
H
1

Using Pipes and No other installations.

LocalizedDatePipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { Locale } from 'src/app/contentful/interfaces/locale';

@Pipe({
  name: 'localizedDate',
})
export class LocalizedDatePipe implements PipeTransform {
  transform(value: any, locale: any): any {
    const date = new Date(value);
    const options: Intl.DateTimeFormatOptions = {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
    };
    return date.toLocaleDateString(locale, options);
  }
}

Search-overlay.component.html

<span *ngIf="card.date" class="hero-cards-carousel__date">
 {{ card.date | localizedDate: vm.locale?.code }}
 </span>

Result

"20. Dez. 2012"

Hearthstone answered 31/1, 2023 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.