How to set language globally for moment.js

烂漫一生 提交于 2020-07-05 03:08:16

问题


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


回答1:


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



回答2:


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.




回答3:


To build onto the answer by Gapur, how I got it to work (React native) was like this,

... other imports
import moment from "moment";
import russianLocale from "moment/locale/ru";
import englishLocale from "moment/locale/en-gb";
import chineseLocale from "moment/locale/zh-cn";

const Component = ({ ...props, language }) => {
  moment.locale(language);

... logic

// wherever 'moment' is used, it's displayed in 
// the language that is indicated by the language prop

... other logic

moment version 2.24.0




回答4:


for example I want to use 'fa' locale

import moment from 'moment'
import fa from 'moment/locale/fa'

moment.locale('fa', fa) 


来源:https://stackoverflow.com/questions/41595585/how-to-set-language-globally-for-moment-js

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!