Angular 中的日期格式
 
我们将介绍如何使用、更改或添加元素,并使用 Angular 中的 DatePipe 以日期格式显示 timezone 中的日期。
Angular 中的日期管道
Angular 日期管道用于根据提供的日期格式、时区和国家/地区信息在 Angular 中格式化日期。
使用 DatePipe,我们可以根据给定的预定义 Angular 日期格式或自定义 Angular 日期格式轻松转换日期对象、数字或 ISO 日期字符串。
Angular DatePipe 接受三个参数:format、timezone 和 locale。
format
我们可以在格式参数中传递预定义的日期格式或自定义的日期格式。
timezone
在 timezone 参数中,默认时区是用户机器的本地系统时区。我们可以通过传递时区 offset (‘0510’) 或标准 UTC/GMT (CET) 或美国大陆时区缩写来更改时区,它是一个可选参数。
locale
locale 表示要使用的语言环境格式规则。如果设置或未定义,语言环境的默认值是我们的项目语言环境 (en_US)。语言环境是一个可选参数。
Angular 日期管道示例
我们将讨论一些具有不同日期格式的示例,以更好地理解 Angular DatePipe。
首先,我们将在我们的 app.component.ts 中添加此代码。
#angular
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  today: Date = new Date();
  pipe = new DatePipe('en-US');
  todayWithPipe = null;
  ngOnInit(): void {
    this.todayWithPipe = this.pipe.transform(Date.now(), 'dd/MM/yyyy');
  }
}
我们在上面的代码中从@angular/common 导入了 DatePipe。我们导出了一个在 Initial 上实现的类 AppComponent,在其中我们创建了一个具有 en-US 语言环境的新 DatePipe。
我们将向 app.component.html 添加代码,以使用我们预定义的日期格式 dd/MM/yyyy 显示日期。
<div>Today Date is: {{ todayWithPipe }}</div>
输出:

Angular 中的预定义日期格式列表
| 日期格式 | 结果 | 
|---|---|
| M/d/yy, h:mm a | 12/2/21, 4:38 PM | 
| MMM d, y, h:mm:ss a | Dec 2, 2021, 4:39:12 PM | 
| MMMM d, y, h:mm:ss a z | December 2, 2021, 4:39:35 PM GMT+5 | 
| EEEE, MMMM d, y, h:mm:ss a zzzz | Thursday, December 2, 2021, 4:39:55 PM GMT+05:00 | 
| M/d/yy | 12/2/21 | 
| MMM d, y | Dec 2, 2021 | 
| MMMM d, y | December 2, 2021 | 
| EEEE, MMMM d, y | Thursday, December 2, 2021 | 
| h:mm a | 4:42 PM | 
| h:mm:ss a | 4:43:52 PM | 
| h:mm:ss a z | 4:44:32 PM GMT+5 | 
| h:mm:ss a zzzz | 4:45:00 PM GMT+05:00 | 
Angular DatePipe 有 12 种预定义格式,如上表所示。但我们也可以创建自定义日期格式并包含更多元素,如年代、年周、月周、月日等。
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn