Angular应用中如何格式化得到01 Sep, 2021格式的日期
Angular 使用 DatePipe 实现 01 Sep, 2021 格式日期展示
前置依赖准备
首先确保对应功能模块中已经导入 CommonModule,Angular 内置的 DatePipe 包含在该包中:
// app.module.ts 示例 import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { CommonModule } from '@angular/common'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, CommonModule], bootstrap: [AppComponent] }) export class AppModule { }
模板中直接调用(推荐方案)
你需要的日期格式对应的 DatePipe 格式符为 dd MMM, yyyy,直接在模板中用管道语法调用即可:
- 组件中定义日期变量
// app.component.ts 示例 import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { // 示例日期:2021年9月1日,注意Angular月份从0开始计数,8对应9月 demoDate = new Date(2021, 8, 1); }
- 模板中使用管道格式化
<!-- app.component.html 示例 --> <span>{{ demoDate | date: 'dd MMM, yyyy' }}</span>
上述代码运行后输出效果为:
01 Sep, 2021
组件类中调用(可选)
如果需要在TS逻辑中先格式化再使用,可以将DatePipe作为服务注入调用:
- 在模块providers中注册DatePipe
// app.module.ts 新增配置 import { DatePipe } from '@angular/common'; @NgModule({ // 其他原有配置不变 providers: [DatePipe] })
- 组件中注入并调用
// app.component.ts 示例 import { Component, OnInit } from '@angular/core'; import { DatePipe } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent implements OnInit { formattedDate: string | null = ''; constructor(private datePipe: DatePipe) {} ngOnInit() { const demoDate = new Date(2021, 8, 1); this.formattedDate = this.datePipe.transform(demoDate, 'dd MMM, yyyy'); // 此时formattedDate的值为 '01 Sep, 2021' } }
注意事项
- 格式符严格区分大小写:
MMM对应短英文月份缩写,小写mmm为无效格式;dd对应两位日期、yyyy对应四位年份 - 默认使用
en-USlocale,所以月份显示为Sep、Oct这类英文缩写,需要其他语言可以自行配置LOCALE_ID切换 - 日期构造函数中月份参数从0开始计数,1月对应0、12月对应11,不要填错导致日期偏移
内容的提问来源于stack exchange,提问作者Yogesh Nikam
相关产品推荐
相关产品推荐

