You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Moment.js或原生Intl实现小时的复数化并支持本地化?

实现小时复数本地化的两种方案

当然没问题!不管是用Moment.js还是原生的Intl API,都能完美实现你要的小时复数本地化需求,我给你分别拆解具体实现方式:

一、用Moment.js实现

Moment.js本身内置了各种语言的复数规则,我们可以直接利用它的本地化能力来扩展一个自定义方法:

步骤1:确保加载对应语言的本地化文件

如果要支持俄语,需要先引入俄语的本地化包(比如在项目里导入moment/locale/ru,或者在HTML中引入对应的CDN脚本)。

步骤2:扩展Moment的静态方法

// 扩展Moment的自定义方法
moment.specialFunction = function(options) {
  const hours = options.hours;
  // 获取当前语言的本地化规则
  const localeData = moment.localeData();
  // 根据小时数获取对应的复数形式单词
  // 第四个参数false表示不使用"relative time"的前缀(比如"in"、"ago")
  const hourLabel = localeData.relativeTime(hours, false, 'h', false);
  // 拼接数字和本地化后的单词
  return `${hours} ${hourLabel}`;
};

测试效果

// 切换到英文环境
moment.locale('en');
console.log(moment.specialFunction({hours: 1})); // 输出:1 hour
console.log(moment.specialFunction({hours: 2})); // 输出:2 hours

// 切换到俄语环境
moment.locale('ru');
console.log(moment.specialFunction({hours: 1})); // 输出:1 час
console.log(moment.specialFunction({hours: 2})); // 输出:2 часа
console.log(moment.specialFunction({hours: 5})); // 输出:5 часов

Moment.js会自动处理不同语言的复数规则(比如俄语的复数有三种形式),不需要你手动判断数字范围,非常省心。

二、用原生Intl API实现

如果你不想依赖第三方库,原生的Intl.PluralRules和Intl.DisplayNames组合就能搞定,更轻量且兼容性优秀:

实现代码

function formatHours(hours, locale = 'en') {
  // 创建对应语言的复数规则实例,指定单位类型为"hour"
  const pluralRules = new Intl.PluralRules(locale, {
    type: 'unit',
    unit: 'hour'
  });
  // 获取当前小时数对应的复数类别(比如英文的"one"/"other",俄语的"one"/"few"/"many")
  const pluralCategory = pluralRules.select(hours);

  // 创建本地化单位名称实例
  const displayNames = new Intl.DisplayNames(locale, { type: 'unit' });

  // 根据复数类别获取对应的本地化单位名称
  let unitLabel;
  switch (pluralCategory) {
    case 'one':
      unitLabel = displayNames.of('hour');
      break;
    case 'few':
      unitLabel = displayNames.of('hour-few') || displayNames.of('hour');
      break;
    case 'many':
      unitLabel = displayNames.of('hour-many') || displayNames.of('hour');
      break;
    default:
      unitLabel = displayNames.of('hour');
  }

  return `${hours} ${unitLabel}`;
}

测试效果

console.log(formatHours(1, 'en')); // 输出:1 hour
console.log(formatHours(2, 'en')); // 输出:2 hours
console.log(formatHours(1, 'ru')); // 输出:1 час
console.log(formatHours(2, 'ru')); // 输出:2 часа
console.log(formatHours(5, 'ru')); // 输出:5 часов

这种方案不需要任何外部依赖,现代浏览器(Chrome、Firefox、Edge、Safari 14+)都能完美支持,适合追求轻量的项目。


内容的提问来源于stack exchange,提问作者Nikita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 01:14:07