netAction
netAction

Reputation: 1877

How to run momentJs with two languages or duplicate moment()?

I need two instances of momentJs with slightly different language settings and tried this according to the documentation:

var moment2 = moment();
moment2.lang('en', { ... });

Where is the moment("2014-05-22") function in moment2?

I need something like this:

moment2("2014-05-22").calendar();

Upvotes: 0

Views: 683

Answers (2)

link
link

Reputation: 1676

moment.lang provides instance specific configuration, so you do not set it relatively to the factory function, but to the single moment instance.

I think you should do something like:

var local = moment('2014-05-22');
local.lang('fr', { calendar : {
  lastDay : '[new]',
  sameDay : '[new]',
  nextDay : '[new]',
  lastWeek : '[new]',
  nextWeek : '[new]',
  sameElse : '[new]'
}});
console.log(local.calendar());

The result:

"vendredi à 00:00"

It is french, but it should be "new".

Update

The code above will not work because momentjs doesn't allow to patch an existing language to define your own calendar. You have to set a new language. They really need to point this out in the documentation. See this issue on github

Upvotes: 2

netAction
netAction

Reputation: 1877

I have a solution that really works. It overwrites momentJs's global language setting on every calendar() call.

moment.lang('de');

// internationalisation objects for momentJs calendar view WITHOUT time:
var momentShort = {
    'de': {
        calendar : {
            sameDay: "[heute]",
            sameElse: "L",
            nextDay: '[morgen]',
            nextWeek: 'dddd',
            lastDay: '[gestern]',
            lastWeek: '[letzten] dddd'
        }
    },
    'en' : {
        calendar : {
            sameDay : '[today]',
            nextDay : '[tomorrow]',
            nextWeek : 'dddd',
            lastDay : '[yesterday]',
            lastWeek : '[last] dddd',
            sameElse : 'L'
        }
    }
};

// internationalisation objects for momentJs calendar view WITH time:
var momentFull = {
    'de': {
        calendar : {
            sameDay: "[heute um] LT",
            sameElse: "L",
            nextDay: '[morgen um] LT',
            nextWeek: 'dddd [um] LT',
            lastDay: '[gestern um] LT',
            lastWeek: '[letzten] dddd [um] LT'
        },
    },
    'en' : {
        calendar : {
            sameDay : '[today at] LT',
            nextDay : '[tomorrow at] LT',
            nextWeek : 'dddd [at] LT',
            lastDay : '[yesterday at] LT',
            lastWeek : '[last] dddd [at] LT',
            sameElse : 'L'
        }
    }
};


moment.lang(moment.lang(), momentShort[moment.lang()]);
var cal = moment("2014-05-23");
console.log( cal.calendar() );


moment.lang(moment.lang(), momentLong[moment.lang()]);
var cal = moment("2014-05-23");
console.log( cal.calendar() );

Upvotes: 0

Related Questions