简体   繁体   English

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

[英]Use “5 days ago (Tue)” if within the last week in moment.js

I'm using moment.js. 我正在使用moment.js。

The default for relative past days is "5 days ago" . 相对过去几天的默认值是"5 days ago" But what I want is that if it's within a week ago it should return "5 days ago (Tue)" . 但我想要的是,如果它在一周前它应该返回"5 days ago (Tue)" If it's more than a week, I want the regular "5 days ago" . 如果超过一周,我想要常规的"5 days ago"

The docs say I can supply a function to custom format such a thing: 文档说我可以提供一个函数来自定义格式这样的东西:

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"
    }
});

The problems are: 问题是:

  • How do I calculate the weekday name for variable FOO ? 如何计算变量FOO的工作日名称?
  • It returns eg 5 days (Mon) ago instead of 5 days ago (Mon) 它返回例如5 days (Mon) ago而不是5 days ago (Mon)
  • I want this custom format only if it's <= 7 days (within the last week) 我希望这个自定义格式只有在<= 7天(在上周内)

You can't manipulate the relative time format in the way you asked. 您无法以您提出的方式操纵相对时间格式。 However, you can simply do the comparison yourself to decide whether or not to append the additional string. 但是,您可以自己进行比较,以决定是否附加其他字符串。

// 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)") : "");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM