javascript - 如果在 moment.js 的最后一周内使用 "5 days ago (Tue)"

标签 javascript momentjs

我正在使用 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/

相关文章:

javascript - Momentjs isDST 函数不返回正确的结果

TypeScript:如何将现有命名空间设为全局?

javascript - CET 时区中的日期到用户时区的日期

javascript - onClick 不触发 react 功能组件内定义的函数

javascript - jsPDF 显示处理时加载。 promise 不等待

javascript - 将值插入多维数组

javascript - 如果我将输入类型数字的值存储在另一个变量中,它会在末尾缺少一个数字

javascript - 基于另一个对象数组创建对象数组

reactjs - moment 对象抛出错误 'toDate' 不是函数

javascript - UTC 到 EST Moment.js