javascript - 使用 IntlDateTimeFormat 返回 AM/PM

标签 javascript datetime

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

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

2022 年 9 月 27 日中午 12:20

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

2022 年 9 月 27 日 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'用于“早上”、“上午”、“中午”、“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());

关于javascript - 使用 IntlDateTimeFormat 返回 AM/PM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73867003/

相关文章:

javascript - 如何随机验证动态行

asp.net - Gridview BoundField 在编辑/更新模式下从日期时间中删除时间

c# - 获取今天之后第 n 个星期日的 DateTime

python pandas时间序列年提取

.net - 如何在 .net Web 服务中序列化可为 null 的 DateTime?

javascript - 嵌套函数提升是否影响全局变量(在同一函数中声明)?

javascript - 我可以在 Angular 1.x 的 ng-model 中使用 {{variable name}}

c# - 使用 Datetime.UTC 设置中非西部时间

Javascript 不会火?

javascript - 使用 Apollo,我如何区分新创建的对象?