How do I change the language of moment.js?

前端 未结 20 1417
别那么骄傲
别那么骄傲 2020-11-29 16:27

I am trying to change the language of the date which is being set by moment.js. The default one is English, but I want to set the German language. These is what I tried:

相关标签:
20条回答
  • 2020-11-29 17:09

    I had to import also the language:

    import moment from 'moment'
    import 'moment/locale/es'  // without this line it didn't work
    moment.locale('es')
    

    Then use moment like you normally would

    alert(moment(date).fromNow())
    
    0 讨论(0)
  • 2020-11-29 17:11

    With moment 2.18.1 and onward:

      moment.locale("de");
      var m = moment().format("LLL")
    
    0 讨论(0)
  • 2020-11-29 17:11

    This one just works by auto detecting the current user location.

    import moment from "moment/min/moment-with-locales";
    
    // Then use it as you always do. 
    moment(yourDate).format("MMMM Do YYYY, h:mm a")
    
    0 讨论(0)
  • 2020-11-29 17:11

    Whoops slip of the pen. I'd solve this: var moment = function(x) { return moment(x).locale('de'); } The other ways don't really seem to stick/hold under conditions (for me).

    0 讨论(0)
  • 2020-11-29 17:14

    You'd need to add moment.lang(navigator.language) in your script.

    And must also add each country locale you want to display in : for example for GB or FR, you need to add that locale format in moment.js library. An example of such format is available in momentjs documentation. If you don't add this format in moment.js then it'd ALWAYS pick up US locale as that's the only one that I currently see.

    0 讨论(0)
  • 2020-11-29 17:14
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>MomentJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
        <script type="text/javascript" src="moment.js"></script>
        <script type="text/javascript" src="locale/ne.js"></script>
    </head>
    <body>
        <script>
            jQuery(document).ready(function($) {
                moment.locale('en'); // default the locale to English
                var localLocale = moment();
    
                moment.locale('ne'); // change the global locale to Nepalese
                var ne1 = localLocale.format('LLLL');
                var ne2 = moment().format('LLLL');
    
                $('.ne1').text(ne1);
                $('.ne2').text(ne2);
            });
        </script>
        <p class="ne1"></p>
        <p class="ne2"></p>
    </body>
    </html>
    

    Demo

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