为fromNow()创建自定义语言环境的momentjs中的最佳实践是什么,但是还能够在其他地方使用标准语言环境?
我希望能够使用正常的fromNow(“几天前”),还能使用“短”fromNow(“1d +”)...意思是超过一天前。我得到了它的工作,但现在每当我使用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 :(得分: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