Angular中如何获取shortDate等预定义日期格式的实际格式化规则?
如何获取Angular中
shortDate等预定义日期格式对应的实际格式规则 当我们将日期格式化为shortDate(或其他任意预定义格式化类型)时,不同地区语言环境下的展示格式存在差异,示例如下:
- "de"语言环境下格式为13.10.21 (DD.MM.YYYY)
- "en-US"语言环境下格式为10/13/21 (MM/DD/YYYY)
- "en-GB"语言环境下格式为13/10/2021 (DD/MM/YYYY)
多语言产品中用户无法直观感知当前生效的日期格式,容易造成使用困惑,我们需要向用户展示对应的格式规则,但formatDate依赖的底层getNamedFormat函数未对外导出,无法直接调用获取。
解决方案
Angular官方在@angular/common包中提供了公开的区域配置API,可直接调用getLocaleDateFormat获取指定语言环境下的预定义日期格式规则:
第一步:导入依赖
import { Component, Inject, LOCALE_ID } from '@angular/core'; import { formatDate, getLocaleDateFormat, FormatWidth } from '@angular/common';
第二步:调用API获取格式规则
FormatWidth枚举值和预定义日期格式的对应关系为:
shortDate对应FormatWidth.ShortmediumDate对应FormatWidth.MediumlongDate对应FormatWidth.LongfullDate对应FormatWidth.Full
使用示例代码如下:
@Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { deDate: string; enDate: string; enGbDate: string; // 存储对应区域的日期格式规则 deShortDateFormat: string; enUsShortDateFormat: string; enGbShortDateFormat: string; // 当前生效区域的日期格式 currentShortDateFormat: string; constructor(@Inject(LOCALE_ID) private currentLocale: string) { const targetDate = Date.now(); // 原有格式化逻辑 this.deDate = formatDate(targetDate, 'shortDate', 'de'); this.enDate = formatDate(targetDate, 'shortDate', 'en-US'); this.enGbDate = formatDate(targetDate, 'shortDate', 'en-GB'); // 获取不同区域的shortDate格式规则 this.deShortDateFormat = getLocaleDateFormat('de', FormatWidth.Short); this.enUsShortDateFormat = getLocaleDateFormat('en-US', FormatWidth.Short); this.enGbShortDateFormat = getLocaleDateFormat('en-GB', FormatWidth.Short); // 获取当前生效区域的shortDate格式规则 this.currentShortDateFormat = getLocaleDateFormat(this.currentLocale, FormatWidth.Short); } }
如果需要获取时间类预定义格式的规则,可使用同包下的getLocaleTimeFormat API,用法和上述一致。该方案为官方公开支持的能力,不存在依赖内部未导出方法的兼容性风险。
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

