繁体   English   中英

使用 IntlDateTimeFormat 返回 AM/PM

[英]Returning AM/PM with IntlDateTimeFormat

我正在使用带有一些日期和时间选项的IntlDateTimeFormat 但是,我很难最终获得我想要的格式。

以下是我目前拥有的代码。 我追求的结果是返回具有以下格式的字符串:

Sept 27, 2022 at 12:20 PM

到目前为止,当前代码正在返回:

27 Sept 2022 at 12:20

请注意缺少AM/PM (大写也会很棒)

  public dateOptions = {
    month: 'short',
    year: 'numeric',
    day: '2-digit',
  } as const;

  public timeOptions = {
    hour: 'numeric',
    minute: 'numeric',
    dayPeriod: 'narrow',
  } as const;

  private newDateString() {
    const now = new Date();
    const tz = Intl.DateTimeFormat().resolvedOptions().locale;
    const date = Intl.DateTimeFormat(tz, this.dateOptions).format(now);
    const time = Intl.DateTimeFormat(tz, this.timeOptions).format(now);
    return `${date}` + ' at ' + `${time}`;
  }

删除了dayPeriod: 'narrow'然后添加选项以使用 12 小时格式的时间hourCycle: 'h12'

  • dayPeriod: 'narrow'会将时间格式化为文本格式,具体取决于语言环境。
  • hourCycle: 'h12' | 'h11' | 'h23' | 'h24' hourCycle: 'h12' | 'h11' | 'h23' | 'h24'将以 12/24 小时格式格式化时间

 var dateOptions = { month: 'short', year: 'numeric', day: '2-digit', }; var timeOptions = { hour: 'numeric', minute: 'numeric', hourCycle: 'h12' }; function newDateString() { const now = new Date(); const tz = Intl.DateTimeFormat().resolvedOptions().locale; const date = Intl.DateTimeFormat(tz, this.dateOptions).format(now); const time = Intl.DateTimeFormat(tz, this.timeOptions).format(now); console.log(`${date}` + ' at ' + `${time}`); } newDateString(new Date())

dayPeriod: 'narrow'用于“in the morning”、“am”、“noon”、“n”等白天时段的格式样式,将其更改为hour12: true

 dateOptions = { day: '2-digit', year: 'numeric', month: 'short', } timeOptions = { hour: 'numeric', minute: 'numeric', hour12: true //dayPeriod: 'narrow', } function newDateString(tz) { const now = new Date(); //const tz = Intl.DateTimeFormat().resolvedOptions().locale; const date = Intl.DateTimeFormat(tz, this.dateOptions).format(now); const time = Intl.DateTimeFormat(tz, this.timeOptions).format(now); return `${date} at ${time}`; } function justAnExampleAsTheOpWatnsThis() { const now = new Date(); const date = Intl.DateTimeFormat("en-GB", this.dateOptions).format(now); const time = Intl.DateTimeFormat("en-US", this.timeOptions).format(now); return `${date} at ${time}`; } console.log(newDateString("en-US")); console.log(newDateString("en-GB")); console.log("Op want this:" + justAnExampleAsTheOpWatnsThis());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM