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

使用Moment.js获取相对时间时如何将'an hour ago'改为'1 hour ago'

Moment.js 相对时间显示规则修改方案

Moment.js的相对时间输出内容由本地化配置的relativeTime对象控制,默认单数时间单位会使用a/an作为前缀,只需重写对应配置即可实现需求。

  • 全局生效配置
    直接更新全局的英文本地化规则,所有调用Moment相对时间的地方都会自动生效:
import moment from 'moment';

moment.updateLocale('en', {
  relativeTime: {
    future: 'in %s',
    past: '%s ago',
    s: '1 second',
    ss: '%d seconds',
    m: '1 minute',
    mm: '%d minutes',
    h: '1 hour', // 将默认的'an hour'改为'1 hour'
    hh: '%d hours',
    d: '1 day',
    dd: '%d days',
    w: '1 week',
    ww: '%d weeks',
    M: '1 month', // 将默认的'a month'改为'1 month'
    MM: '%d months',
    y: '1 year',
    yy: '%d years'
  }
});

配置完成后测试效果:
moment().subtract(1, 'hour').fromNow() → 输出1 hour ago
moment().subtract(1, 'month').fromNow() → 输出1 month ago

  • 局部生效配置
    如果不希望修改全局规则,可以单独定义自定义本地化实例使用:
import moment from 'moment';

// 定义继承英文规则的自定义本地化
const customMoment = moment.defineLocale('custom-en', {
  parentLocale: 'en',
  relativeTime: {
    future: 'in %s',
    past: '%s ago',
    s: '1 second',
    ss: '%d seconds',
    m: '1 minute',
    mm: '%d minutes',
    h: '1 hour',
    hh: '%d hours',
    d: '1 day',
    dd: '%d days',
    w: '1 week',
    ww: '%d weeks',
    M: '1 month',
    MM: '%d months',
    y: '1 year',
    yy: '%d years'
  }
});

// 调用自定义实例获取相对时间
customMoment().subtract(1, 'hour').fromNow(); // 返回1 hour ago

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:18:00