timmyg13
timmyg13

Reputation: 503

Momentjs two instances, different fromNow

what is the best practice in momentjs for creating a custom locale for fromNow() but also being able to use the standard one in other places?

I want to be able to use the normal fromNow ("a few days ago") but also a "short" fromNow ("1d+") ... meaning more than a day ago. I got it working, but now whenever I use fromNow() it always uses the "short" fromNow version

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()

I have tried (unsuccessfully) using .clone() function

Upvotes: 0

Views: 1010

Answers (1)

Vinny M
Vinny M

Reputation: 770

Define a custom locale and then either switch back and forth using .locale() or have two moment() variables.

Something like this:

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 

Upvotes: 3

Related Questions