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

day.js不支持周单位相对时间,如何配置实现类似moment.js的周相对时间输出?

报错的核心原因是day.js的RelativeTime插件默认未在本地化配置中定义周单位对应的显示模板,解析到周单位阈值时找不到对应的格式化逻辑,因此抛出类型错误。

可行的解决方案如下:

步骤1:补全本地化配置中的周单位模板

根据你使用的语言,给relativeTime配置补充周单位的显示规则,以下分别是英文和中文的配置示例:

英文环境配置

import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'

// 补全英文环境下的周单位模板,保留原有默认配置
dayjs.locale('en', {
  relativeTime: {
    ...dayjs.Ls.en.relativeTime,
    w: '1 week',
    ww: '%d weeks'
  }
}, null, true)

中文环境配置

import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'

dayjs.locale('zh-cn', {
  relativeTime: {
    future: '%s后',
    past: '%s前',
    s: '几秒',
    ss: '%d秒',
    m: '1分钟',
    mm: '%d分钟',
    h: '1小时',
    hh: '%d小时',
    d: '1天',
    dd: '%d天',
    // 补充周单位配置
    w: '1周',
    ww: '%d周',
    M: '1个月',
    MM: '%d个月',
    y: '1年',
    yy: '%d年'
  }
}, null, true)

步骤2:注册RelativeTime插件并传入自定义配置

注册插件时同时传入你需要的阈值和向下取整规则,和你之前moment.js的配置对齐:

dayjs.extend(relativeTime, {
  // 向下取整,对应moment的relativeTimeRounding(Math.floor)
  rounding: Math.floor,
  thresholds: [
    { l: 's', r: 1 },
    { l: 'ss', r: 59, d: 'second' },
    { l: 'm', r: 1 },
    { l: 'mm', r: 59, d: 'minute' },
    { l: 'h', r: 1 },
    { l: 'hh', r: 23, d: 'hour' },
    { l: 'd', r: 1 },
    { l: 'dd', r: 6, d: 'day' },
    // 周单位阈值配置,小于4周时显示周
    { l: 'w', r: 1},
    { l: 'ww', r: 3, d: 'week'},
    { l: 'M', r: 1 },
    { l: 'MM', r: 11, d: 'month' },
    { l: 'y', r: 1 },
    { l: 'yy', d: 'year' },
  ]
})

配置完成后测试,dayjs().subtract(13, 'day').fromNow() 会输出预期的2 weeks ago(英文环境)或2周前(中文环境),无需再把天的阈值调整为30。


内容的提问来源于stack exchange,提问作者Ubaid ur Rehman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:00:01