2015-06-08 31 views
9

我使用的是moment.js。使用「5天前(週二)」,如果在上週內moment.js

相對過去日期的默認值是"5 days ago"。但我想要的是,如果它在一週之前,它應該返回"5 days ago (Tue)"。如果超過一個星期,我想要正常的"5 days ago"

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 days (Mon) ago代替5 days ago (Mon)
  • 我想這個自定義格式只有當它的< = 7天(一週之內)
+0

當天函數'dd'返回''num days(FOO)「'所以我想你之後得到'ago',因爲你在調用函數之後連接它。如果你想要不同的方式,你應該以另一種方式處理返回的線。 – cnluzon

回答

3

你不能操縱在你問的方式相對時間格式。但是,您可以自己簡單地進行比較以決定是否追加附加字符串。

// 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)") : ""); 
相關問題