【问题标题】:Formatting Date with month names in different languages using date pipe使用日期管道以不同语言使用月份名称格式化日期
【发布时间】:2021-07-20 15:13:30
【问题描述】:

我正在像这样在 html 中显示日期

<span >{{ item.lastModified | date : 'MMM d, y' }}</span>

所以日期显示类似于Jul 20, 2021 现在,当我更改浏览器语言时,我需要将月份更改为该语言,该语言应该是动态选择的,但它以英语显示。我该怎么做?

【问题讨论】:

    标签: angular typescript locale date-pipe


    【解决方案1】:

    你需要设置你的'locale':

    1. 在您的 app.module.ts 中:
        // Import all the languages you need (you can add any language you want i.e: '../locales/en-GB', '/locales/en-US', ... ).
        // In this example, I will use 'es' for Spanish and 'fr' for French:
        import myLocaleEs from '@angular/common/locales/es'
        import myLocaleFr from '@angular/common/locales/fr'
    
        import {registerLocaleData} from '@angular/common/';
    
        registerLocaleData(myLocaleEs);
        registerLocaleData(myLocaleFr);
    
    1. 在您的 HTML 中:
    
        // "en" is always by default, you don't need to register
        {{ fecha | date: "long":"":"en" }}
        
        {{ fecha | date: "long":"":"es" }}
    
        
        {{ fecha | date: "short":"":"fr" }}
    or  {{ fecha | date: 'MMM d, y':"":"fr" }}
    

    全局设置

    这是一种设置“全局”你最喜欢的语言环境的方法(如果它不同于默认的“en”),所以你不需要在每个管道中都写下来:

    您需要添加到 app.module.ts,除了上述所有代码,此导入和 PROVIDERS 部分:

    ...
    import { LOCALE_ID} from '@angular/core';
    ...
    
    ...
    providers: [
        {provide: LOCALE_ID, useValue: 'es'} // Same value you used above ‘es’ or 'fr' or whatever you had registered
      ],
    ...
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-18
      • 2018-06-06
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      相关资源
      最近更新 更多