使用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 agomoment().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
相关产品推荐
相关产品推荐

