我正在使用带有日期和时间选项的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'用于"在上午"、"上午"、"中午"、"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相关问答推荐

我不知道为什么我的JavaScript没有验证我的表单

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

模块与独立组件

点击按钮一次有文本出现和褪色,而不是点击两次?(html,CSS,JavaScript)

在我的html表单中的用户输入没有被传送到我的google表单中

屏幕右侧屏障上的产卵点""

在react JS中映射数组对象的嵌套数据

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

您能在卸载程序(QtInsteller框架)上添加WizardPage吗?

Next.js服务器端组件请求,如何发送我的cookie token?

单个HTML中的多个HTML文件

使用js构造一个html<;ath&>元素并不能使其正确呈现

为什么客户端没有收到来自服务器的响应消息?

使用可配置项目创建网格

Plotly.js栏为x轴栏添加辅助文本

我想为我的Reaction项目在画布上加载图像/视频,图像正在工作,但视频没有

JavaScript -如何跳过某个字符(S)来打乱字符串中的字符

如何从图表中映射一组图表-js使用REACT

Select 所有输入.值

在采购unpept-visalizations.js时遇到问题