How to set language globally for moment.js

后端 未结 4 1523
忘了有多久
忘了有多久 2021-01-02 07:21

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.         


        
相关标签:
4条回答
  • 2021-01-02 07:23

    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();
    
    0 讨论(0)
  • 2021-01-02 07:26

    for example I want to use 'fa' locale

    import moment from 'moment'
    import fa from 'moment/locale/fa'
    
    moment.locale('fa', fa) 
    
    0 讨论(0)
  • 2021-01-02 07:42

    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.

    0 讨论(0)
  • 2021-01-02 07:47

    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

    0 讨论(0)
提交回复
热议问题