Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set language globally for moment.js

Tags:

momentjs

I get for example: 1day ago. What I need is to set for different language, for example for de. Any suggestion how can I do that?

moment(Date.now()).fromNow()

I tried this:

<script>
    var moment = moment();
    moment.locale('de');
</script>

but get an error:

moment is not a function

like image 211
None Avatar asked Jan 11 '17 16:01

None


People also ask

How do I change the language of MomentJS?

In the docs, you can create language specific instances of moment by doing that. If you format first, the language won't process. Alternatively, you could do something like var deMoment = moment(); deMoment. lang('de') and reuse deMoment instead of moment throughout your script.

How do I get locale from moments?

If you are changing locales frequently, you may want to know what locale is currently being used. This is as simple as calling moment. locale without any parameters.

Does MomentJS use local timezone?

By default, moment objects are created in the local time zone. Local time zone - it's a time zone which is set in a browser or on your node.js server. To change the default time zone, use moment.tz.setDefault with a valid time zone.


2 Answers

See official docs on how changing locale globally.

Note that you have to import locale data (e.g. moment-with-locales.min.js)

Here a working example:

moment.locale('de');
console.log(moment(Date.now()).fromNow()); //vor ein paar Sekunden
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment-with-locales.min.js"></script>

You can also use only data for a given locale (e.g. de):

moment.locale('de');
console.log(moment(Date.now()).fromNow()); //vor ein paar Sekunden
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/locale/de.js"></script>

Moreover you are redefining moment in your code, that is incorrect

var moment = moment();
like image 64
VincenzoC Avatar answered Sep 16 '22 14:09

VincenzoC


EDIT: In the current version of moment.js this solution still works but it will output a message to the console that states you should use a new method called updateLocale. So the new solution should look like:

Updated solution

import moment from 'moment';
import localization from 'moment/locale/fr';

moment.updateLocale('fr', localization);

Previous Solution

You can change moment locale globally like that:

import moment from 'moment';
import localization from 'moment/locale/fr';

moment.locale('fr', localization);

I hope this helps you.

like image 27
Gapur Kassym Avatar answered Sep 18 '22 14:09

Gapur Kassym