You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Angular Date管道输出的AM/PM转换为小写形式?

解决Angular Date管道AM/PM小写的问题

你可以通过以下几种方式实现将日期格式中的AM/PM转为小写:

方法1:拆分格式化后拼接(快速实现)

将日期分为两部分格式化,单独把AM/PM部分转为小写后拼接,避免整个日期字符串被小写:

<ng-container *ngIf="date else empty">
  {{ (date | date: 'dd LLLL yyyy hh:mm') + ' ' + (date | date: 'aa').toLowerCase() }}
</ng-container>

方法2:自定义管道(复用性高)

创建一个专门处理AM/PM小写的管道,方便在多个模板中复用:

  1. 生成管道文件:
ng generate pipe lowercaseAmPm
  1. 修改管道逻辑:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'lowercaseAmPm'
})
export class LowercaseAmPmPipe implements PipeTransform {
  transform(value: string): string {
    return value.replace('AM', 'am').replace('PM', 'pm');
  }
}
  1. 在模板中组合使用:
<ng-container *ngIf="date else empty">
  {{date | date: 'dd LLLL yyyy hh:mm aa' | lowercaseAmPm}}
</ng-container>

注意:需要在对应模块的declarations数组中声明这个管道。

方法3:使用Intl.DateTimeFormat自定义格式化

直接在组件中编写格式化方法,通过原生API实现更灵活的控制:
组件代码:

formatDate(date: Date): string {
  return new Intl.DateTimeFormat('en-US', {
    day: '2-digit',
    month: 'long',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: true
  }).format(date).replace('AM', 'am').replace('PM', 'pm');
}

模板调用:

<ng-container *ngIf="date else empty">
  {{ formatDate(date) }}
</ng-container>

内容的提问来源于stack exchange,提问作者Rahul singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:09:30