How do I change the language of moment.js?

前端 未结 20 1497
别那么骄傲
别那么骄傲 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 16:57

    After struggling, this worked for me for moment v2.26.0:

    import React from "react";
    import moment from "moment";
    import frLocale from "moment/locale/fr";
    import esLocale from "moment/locale/es";
    
    export default function App() {
      moment.locale('fr', [frLocale, esLocale]) // can pass in 'en', 'fr', or 'es'
    
      let x = moment("2020-01-01 00:00:01");
      return (
        
    {x.format("LLL")}
    {x.fromNow()}
    ); }

    You can pass in en, fr or es. If you wanted another language, you'd have to import the locale and add it to the array.

    If you only need to support one language it is a bit simpler:

    import React from "react";
    import moment from "moment";
    import "moment/locale/fr"; //always use French
    
    export default function App() {  
      let x = moment("2020-01-01 00:00:01");
      return (
        
    {x.format("LLL")}
    {x.fromNow()}
    ); }

提交回复
热议问题