0

我刚刚从 moment.js 迁移到 day.js。迁移非常顺利,但 day.js 并没有提供以周为单位的相对时间。我在 moment.js 中所做的

       // Round relative time evaluation down
       moment.relativeTimeRounding(Math.floor);
       moment.relativeTimeThreshold('s', 60);
       moment.relativeTimeThreshold('m', 60);
       moment.relativeTimeThreshold('h', 24);
       moment.relativeTimeThreshold('d', 7);
       moment.relativeTimeThreshold('w', 4);
       moment.relativeTimeThreshold('M', 12);

使用上述相对时间配置,我得到了所需的输出,例如2 weeks ago.

迁移到 day.js 后,现在我的配置是

    const 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' },
      { l: 'w', r: 1},
      { l: 'ww', r: 4, d: 'week'},
      { l: 'M', r: 1 },
      { l: 'MM', r: 11, d: 'month' },
      { l: 'y', r: 1 },
      { l: 'yy', d: 'year' },
    ];

在 day.js 中使用上述配置,我收到以下错误。

core.js?7d7a:4073 ERROR TypeError: v is not a function
    at Object.n.fromToBase (VM15721 relativeTime.js:82)
    at i (VM15721 relativeTime.js:32)
    at M.n.from (VM15721 relativeTime.js:93)
    at M.n.fromNow (VM15721 relativeTime.js:103)

当我删除

      { l: 'w', r: 1},
      { l: 'ww', r: 4, d: 'week'},

并将当天的阈值更改为 30,

从 day.js 配置,然后它工作正常,我得到了类似13 days ago.

所以,我的问题是,是否有任何解决方法可以在几周而不是几天内获得输出?

4

1 回答 1

0

updateLocale must be added

dayjs.extend(updateLocale);
dayjs.updateLocale('en', {
    relativeTime: {
      future: 'in %s',
      past: '%s ago',
      s: 'a few seconds',
      m: 'a minute',
      mm: '%d minutes',
      h: 'an hour',
      hh: '%d hours',
      d: 'a day',
      dd: '%d days',
      w: '%d week',
      ww: '%d weeks',
      M: 'a month',
      MM: '%d months',
      y: 'a year',
      yy: '%d years',
    },
  });
于 2022-02-10T08:48:12.823 回答