如果在最后一周内在moment.js中使用"5天前(星期二)"

h b*_*bob 9 javascript momentjs

我正在使用moment.js.

相对过去几天的默认值是"5 days ago".但我想要的是,如果它在一周前它应该返回"5 days ago (Tue)".如果超过一周,我想要常规"5 days ago".

文档说我可以提供一个函数来自定义格式这样的东西:

moment.locale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s:  "seconds",
        m:  "a minute",
        mm: "%d minutes",
        h:  "an hour",
        hh: "%d hours",
        //d:  "a day",   // this is the default
        d:  function(num, noSuffix, key, future) { return "a day (" + FOO + ")"; },
        //dd: "%d days", // this is the default
        dd: function(num, noSuffix, key, future) { return num + "days (" + FOO + ")"; },
        M:  "a month",
        MM: "%d months",
        y:  "a year",
        yy: "%d years"
    }
});
Run Code Online (Sandbox Code Playgroud)

问题是:

  • 如何计算变量的工作日名称FOO
  • 它返回例如5 days (Mon) ago而不是5 days ago (Mon)
  • 我希望这个自定义格式只有在<= 7天(在上周内)

Mat*_*int 4

您无法按照您要求的方式操纵相对时间格式。但是,您可以简单地自己进行比较来决定是否附加附加字符串。

// your source moment
var m = moment("2015-06-04");

// calculate the number of whole days difference
var d = moment().diff(m,'days');

// create the output string
var s = m.fromNow() + (d >= 1 && d <= 7 ? m.format(" (ddd)") : "");
Run Code Online (Sandbox Code Playgroud)