2016-03-01 54 views
0

什麼是在爲fromNow()創建自定義區域設置時的最佳實踐,同時也能夠在其他地方使用標準區域?Momentjs兩個實例,不同於Now

我希望能夠使用來自Now(「前幾天」)的正常情況,而且還可以使用來自Now(「1d +」)的「short」......這意味着一天以前。我懂了工作,但現在每當我使用fromNow()它總是使用「短」 fromNow版本

UI.registerHelper "momentizeFromNow", (ts) -> 
    moment(ts).fromNow() 

UI.registerHelper "momentizeFromNowShort", (ts) -> 
    momentLocal = moment 
    momentLocal.locale('en', relativeTime: 
    future: "in %s" 
    past: "%s" 
    s: "now" 
    m: "1m" 
    mm: "%dm+" 
    h: "1h" 
    hh: "%dh+" 
    d: "1d" 
    dd: "%dd+" 
    w: "%dw" 
    ww: "1w+" 
    M: "1w+" 
    MM: "1w+" 
    y: "1w+" 
    yy: "1w+" 
) 
    momentLocal(ts).fromNow() 

我曾嘗試使用.clone(失敗)()函數

+0

很抱歉,但什麼是'UI.registerHelper'? – Pogrindis

+0

對不起,這只是一個流星的東西 – timmyg13

回答

1

定義一個定製的語言環境和然後使用.locale()來回切換或者有兩個moment()變量。

事情是這樣的:

moment.locale('en-cust', { 
    relativeTime : { 
    future: "in %s", 
    past: "%s", 
    s: "now", 
    m: "1m", 
    mm: "%dm+", 
    h: "1h", 
    hh: "%dh+", 
    d: "1d", 
    dd: "%dd+", 
    w: "%dw", 
    ww: "1w+", 
    M: "1w+", 
    MM: "1w+", 
    y: "1w+", 
    yy: "1w+" 
    } 
}); 
//Defined custom locale as 'en-cust' 

then = moment(1316116057189).locale('en'); 
thenCust = moment(1316116057189).locale('en-cust'); 
//Set variables to moments with specific locales 

console.log(then.fromNow()); 
//4 years ago 
console.log(thenCust.fromNow()); 
//1w+ 
console.log(thenCust.locale('en').fromNow()); 
//4 years ago -> switched locale with chaining method 
console.log(then.locale('en-cust').fromNow()); 
//1w+ -> switched locale with chaining method 
console.log(then.fromNow()); 
//1w+ as it is still set for 'en-cust' from previous chain 
then.locale('en'); 
//Set it back 
console.log(then.fromNow()); 
//4 years ago 
+0

嗯我會認爲這會工作,但它可能是一個問題流星綁定到時刻和全球切換時語言環境改變。有沒有什麼辦法可以延長時間來創建一個新的函數(fromNowShort())? – timmyg13

+1

我對流星不是很熟悉,但它不應該打破我提到的任何鏈條。你測試了'yourMoment.locale('en-cust')。fromNow()'鏈,根據需要切換'locale()'? –

相關問題