根据语言环境使用 am / pm / h 单位格式化 LT 时刻

format LT moment with am / pm / h unit depending on locale

我必须处理 en 和 fr 的两个语言环境,并根据语言环境显示格式化的时间。

我试着这样做:

  const hour = moment({
    hour: 15
  }).format('LT');

fr 显示 15:00,en 显示 3:00pm。我想要 fr 格式的 15h 和 en 的下午 3 点。

我尝试使用updateLocale方法添加特定选项,格式为LT,但无法得出结果。

    const optionsFR = {
      longDateFormat: {
        LT: 'HH:mm',
      },
      meridiem: (): string => 'h',
    }
    
    const optionsEn = {
      longDateFormat: {
        LT: 'h:mm a',
      },
      meridiem: (): string => 'h',
    }

moment.updateLocale(locale, options);

我可以修改 LT 选项,对 en 执行 LT: h a,对 fr 执行 LT: HH。但我无法显示 fr-fr 的 'h' 单位。我必须手动完成吗?

您可以在 longDateFormat.

中使用 LT: 'HH[h]' 获取法语语言环境的 h

如文档的 转义字符 部分所述:

To escape characters in format strings, you can wrap the characters in square brackets.

示例:

const optionsFR = {
  longDateFormat: {
    LT: 'HH[h]',
  }
}

const optionsEn = {
  longDateFormat: {
    LT: 'h a',
  }
}

moment.updateLocale("en", optionsEn);
moment.updateLocale("fr", optionsFR);
const hour = moment({
  hour: 15
});
console.log(hour.locale('fr').format('LT'));
console.log(hour.locale('en').format('LT'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.0/moment-with-locales.min.js"></script>