【问题标题】:How to set dates to locale in Angular?如何在Angular中将日期设置为语言环境?
【发布时间】:2020-05-14 09:16:57
【问题描述】:

所以我有一个角度应用程序(角度 8),将被英国、毛里求斯和南非(可能更多)使用。

如何根据用户的区域设置日期?

我会使用自定义管道吗?或者将其设置为 app.module 中的某种提供程序?

谢谢。

【问题讨论】:

    标签: angular typescript date angular-date-format


    【解决方案1】:

    app.module 中,我将MAT_DATE_LOCALE 的值设置为:

    providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: RequestInterceptor,
          multi: true,
        },
        { provide: MAT_DATE_LOCALE, useValue: 'ro-RO' },  //YOUR DESIRED LOCALE
        DatePipe
      ],
    

    另外,在 mat-table 等其他控件中,我使用管道:

    <td mat-cell *matCellDef="let element" class="alignLeft"> {{ element.Date | date: 'dd/MM/yyyy HH:mm' }}
    

    当内容是动态的时,你可以尝试使用这个:

    import { LOCALE_ID, Inject } from '@angular/core';
    
    ...
    
    constructor(
      @Inject(LOCALE_ID) public locale: string
    ) { }
    

    并将其作为参数发送到自定义管道或其他相关方法。

    让我知道这是否对你有用

    【讨论】:

    • 是的,这与我目前的做法类似,但如果用户在英国,他们需要查看 MM/dd/yyyy,但 SA 必须将其视为 yyyy/MM/dd。跨度>
    • @AustinReid 我已经更新了我的答案。希望这就是你要找的东西
    • 我想我仍然对应用程序如何设置日期感到有些困惑。您能否分享一个 plunkr 或者如果有我可以检查的回购?
    • @AustinReid 我现在没有示例,但我建议尝试使用浏览器 vpn 更改国家/地区并记录返回的区域设置。 angular.io/api/core/LOCALE_ID
    • 我现在正在为此苦苦挣扎,您应该能够告诉 Angular 从用户浏览器中推断出 LOCALE_ID。您必须使其成为引导程序的一部分是没有意义的。这对于将在不同地区使用的应用程序没有好处
    【解决方案2】:

    通常我使用moment 库,并会创建一个管道以所需语言格式化日期,例如

    import { Pipe, PipeTransform } from '@angular/core';
    import * as moment from 'moment';
    
    @Pipe({
        name: 'customdate'
    })
    export class CustomDatePipe implements PipeTransform {
    
        constructor() { }
    
        transform(value: any, lng:string) {
                return moment(value).lang(lng).format("MMM");
            
        }
    }

    例如

    {{item.date | customdate : 'en-us'}} = 三月

    {{item.date | customdate : 'de'}} = März

    {{item.date | customdate : 'es'}} = Marzo

    【讨论】:

    • 通常我也会这样做,但我需要选择用户浏览器的语言环境并有一个通用的 Date() 对象,它会根据它进行设置。
    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 2021-01-27
    • 2016-10-07
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    相关资源
    最近更新 更多