我正在使用 moment.js。
相对过去几天的默认值是“5 天前”
。但我想要的是,如果它是在一周前,它应该返回 “5 天前(星期二)”
。如果超过一周,我想要常规的 “5 天前”
。
The docs say我可以提供一个函数来自定义格式这样的东西:
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"
}
});
问题是:
- 如何计算变量
FOO
的工作日名称? - 它返回例如
5 天(周一)前
而不是5 天前(周一)
- 只有 <= 7 天(上周内)我才需要这种自定义格式
最佳答案
您不能按照您要求的方式操作相对时间格式。但是,您可以自己简单地进行比较,以决定是否附加额外的字符串。
// 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)") : "");
关于javascript - 如果在 moment.js 的最后一周内使用 "5 days ago (Tue)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30702614/