Angular8:全局日期格式配置 [英] Angular8: Global date format config

查看:40
本文介绍了Angular8:全局日期格式配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular8 并想格式化日期和时间,但我必须一次又一次地使用具有相同格式模式的日期管道,如下所示

I am using Angular8 and want to format date and time but I have to use date pipe with same format pattern again and again as shown below

<p>{{ myDate | date: 'dd MMM yyyy, h:mm a' }}</p>
<p>{{ myOtherDate date: 'dd MMM yyyy, h:mm a' }}</p>
<p>{{ otherVar }}</p>
<p>{{ myOtherOtherDate date: 'dd MMM yyyy, h:mm a' }}</p>

和相同的格式 date: 'dd MMM yyyy, h:mm a' 将用于我项目的每个组件.

and same format date: 'dd MMM yyyy, h:mm a' is to be used in each and every component of my project.

有没有办法在我的应用模块的提供者中提供全局配置,就像这样

Is there a way where I can provide a global config in the providers of my App Module, something like this

@NgModule({
    providers: [
        {provide: LOCAL_PIPE_DATE_PATTERN, useValue: 'ddMMyy'},
    ],
})
export class AppModule {}

然后将日期管道用作

<p>{{ myDate | date }}</p>
<p>{{ myOtherDate | date }}</p>
<p>{{ otherVar }}</p>
<p>{{ myOtherOtherDate | date:'MMyyDD' }}</p> (If format changed)

推荐答案

您可以在项目中创建一个新的日期管道并始终初始化格式

You could create a new date pipe in your project and initialize always the format

@Pipe({
    name: "myDate"
})
export class MyDatePipe {

    constructor(private datePipe: DatePipe) {}

    transform(value: any): string {
        let format = "dd MMM yyyy, h:mm a";
        return this.datePipe.transform(new Date(value), format);
    }
}

这篇关于Angular8:全局日期格式配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆