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

PrimeNG日历时间控件AM/PM本地化失效问题求助

PrimeNG日历控件AM/PM本地化不生效的解决方案

问题原因

PrimeNG的Calendar组件中,可见的AM/PM文本默认依赖浏览器的Intl.DateTimeFormat API或Angular的DatePipe生成,你通过PrimeNGConfig.setTranslation()设置的am/pm值仅用于无障碍(aria-label)属性,不会作用于页面上显示的文本,这就是设置后无效果的核心原因。

解决方案

方案一:自定义时间模板(最直接可控)

利用PrimeNG Calendar的pTemplate="time"模板,完全自定义时间显示内容,直接指定AM/PM的文本:

<p-calendar [(ngModel)]="selectedDate" showTime="true">
  <ng-template pTemplate="time" let-time="time">
    <!-- 处理12小时制小时:0点显示为12 -->
    <span>{{ time.hour > 12 ? time.hour - 12 : time.hour || 12 }}</span>
    <span>:</span>
    <!-- 分钟补零处理 -->
    <span>{{ time.minute.toString().padStart(2, '0') }}</span>
    <!-- 自定义AM/PM文本 -->
    <span class="ml-2">{{ time.hour >= 12 ? 'p.m.' : 'a.m.' }}</span>
  </ng-template>
</p-calendar>

方案二:配置Angular本地化规则

通过修改Angular的LOCALE_ID对应的本地化数据,让DatePipe生成的AM/PM文本符合需求:

  1. 在根模块(如AppModule)中导入并注册自定义本地化数据:
import { LOCALE_ID, NgModule } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeEn from '@angular/common/locales/en';
import localeEnExtra from '@angular/common/locales/extra/en';

// 复制原有扩展数据,修改AM/PM的缩写格式
const customEnExtra = {
  ...localeEnExtra,
  dayPeriods: {
    narrow: { am: 'a', pm: 'p' },
    abbreviated: { am: 'a.m.', pm: 'p.m.' },
    wide: { am: 'ante meridiem', pm: 'post meridiem' }
  }
};

registerLocaleData(localeEn, 'en-US', customEnExtra);

@NgModule({
  providers: [
    { provide: LOCALE_ID, useValue: 'en-US' }
  ]
})
export class AppModule { }
  1. 在Calendar组件上指定包含AM/PM的时间格式:
<p-calendar [(ngModel)]="selectedDate" timeFormat="hh:mm a" showTime="true"></p-calendar>

方案三:全局扩展Calendar组件(适合全项目统一修改)

创建自定义组件继承PrimeNG的Calendar,重写时间格式化方法实现全局替换:

import { Component } from '@angular/core';
import { Calendar } from 'primeng/calendar';

@Component({
  selector: 'app-custom-calendar',
  templateUrl: './custom-calendar.component.html',
  styleUrls: ['./custom-calendar.component.css']
})
export class CustomCalendarComponent extends Calendar {
  override formatTime(time: Date): string {
    const originalFormatted = super.formatTime(time);
    // 替换默认的AM/PM为自定义文本
    return originalFormatted.replace('AM', 'a.m.').replace('PM', 'p.m.');
  }
}

之后在项目中使用<app-custom-calendar>替代原生的<p-calendar>即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 10:37:16