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

如何在Moment.js的calendar()中移除时间并本地化显示今日/明日

解决Moment.js本地化显示“Today”“Tomorrow”(无时间)的问题

方案1:调用本地化内置文本+日期判断

Moment每个语言包都内置了“今天”“明天”的本地化字符串,我们可以直接取用这些文本,再结合日期判断逻辑输出:

// 先切换到目标语言,比如阿拉伯语
// moment.locale('ar');

function getLocalizedDayLabel(date) {
  const now = moment();
  const targetDate = moment(date);

  if (targetDate.isSame(now, 'day')) {
    // 获取本地化的“今天”文本,移除自带的方括号
    return moment.localeData()._calendar.today.replace(/\[|\]/g, '');
  } else if (targetDate.isSame(now.clone().add(1, 'day'), 'day')) {
    // 获取本地化的“明天”文本,移除自带的方括号
    return moment.localeData()._calendar.tomorrow.replace(/\[|\]/g, '');
  }
  // 非今天/明天的日期,按需返回格式化结果
  return targetDate.format('L');
}

方案2:正确配置calendar方法,保留本地化

你之前的问题是硬编码英文文本导致本地化失效,正确做法是在calendar的自定义格式里引用本地化字符串:

// 先切换到目标语言,比如乌克兰语
moment.locale('uk');

const formattedDate = moment(date).calendar(null, {
  sameDay: () => `[${moment.localeData()._calendar.today.replace(/\[|\]/g, '')}]`,
  nextDay: () => `[${moment.localeData()._calendar.tomorrow.replace(/\[|\]/g, '')}]`,
  // 其他场景(如上周/下周)可按需配置
  sameElse: 'L'
});

为啥之前的方法失效?

  • 硬写nextDay: '[Tomorrow]'等于直接覆盖了本地化文本,自然无法适配其他语言。
  • moment(date).calendar('uk', { ... })用错了API:calendar的第一个参数是参考日期,不是语言代码。切换语言必须先调用moment.locale('uk')。

注意事项

  • 必须引入对应语言的Moment本地化包(比如moment/locale/ar.js),否则会自动 fallback 到英文。
  • 少数语言的_calendar结构可能有细微差别,调试时可以用console.log(moment.localeData()._calendar)查看具体内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:33:10