doniyor
doniyor

Reputation: 37856

How do I change the language of moment.js?

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:

var now = moment().format("LLL").lang("de");

It’s giving NaN.

var now = moment("de").format("LLL");

This isn’t even reacting.

var now = moment().format("LLL", "de");

No change: this is still producing a result in English.

How is this possible?

Upvotes: 322

Views: 798827

Answers (24)

Oscar Javier Jimenez
Oscar Javier Jimenez

Reputation: 149

Please try:

import moment from 'moment/moment';
import 'moment/locale/es';

I found the solution from https://es.stackoverflow.com/questions/117997/c%C3%B3mo-utilizar-momentjs-con-fechas-en-espa%C3%B1ol

Upvotes: 3

Alan P.
Alan P.

Reputation: 3123

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 (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}

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 (
    <div className="App">
      {x.format("LLL")}
      <br />
      {x.fromNow()}
    </div>
  );
}

-- UPDATE --

In one case, importing all the locale files like above would resort in the last imported locale always being used (i.e. "es" in the above example), even though I was setting it to "fr". The solution that seems to work is:

import moment from 'moment';
import 'moment/min/locales';

...

moment.locale('fr');

Upvotes: 24

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20088

We can use moment.locale() method to pass your own language ex. I'm using window.navigator.language (ex.en-US) to pass lange at run time.

const formatDate = date => moment(date).locale(window.navigator.language).format('LL')

Upvotes: 0

Taha
Taha

Reputation: 451

I am not sure what changed but importing the language file like this worked for me

import 'moment/src/locale/fr';
moment.locale('fr')

Notice the src in the import statement

Upvotes: 5

Agu Dondo
Agu Dondo

Reputation: 13569

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

console.log(moment(date).fromNow())

Upvotes: 409

Bhanu pratap
Bhanu pratap

Reputation: 79

To change the locale using moment (version later then 2.8.0) perform below steps.

  1. load moment locale files in index.html as below <script src="../node_modules/moment/locale/it.js"></script>

  2. Set locale as required - moment.locale('it');

  3. Now moment.locale() will return "it"

  4. You can use moment with any language like - JavaScript, Angular, node etc.

Upvotes: 1

Ashik Mahmud
Ashik Mahmud

Reputation: 127

First Call , p5.js and moment-with-locales.js and then do code like below and you will get your result.

In this result I have showed Month Name in different language :)

Check code please :

     var monthNameEnglish = moment().locale('en-gb').format('MMMM');
    document.getElementById('monthNameEnglish').innerHTML =  monthNameEnglish;
    
    
         var monthNameGerman = moment().locale('de').format('MMMM');
    document.getElementById('monthNameGerman').innerHTML =  monthNameGerman;
<!DOCTYPE html>
<html>
    <head>
        <title>P5.js and Moment.js</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment-with-locales.js"></script>
    
    <h3>English Version Month Name</h3>
    
    <p id="monthNameEnglish"></p>
    
    <h3> German Version Month Name</h3>
    
    <p id="monthNameGerman"></p>
        
    </head>
    <body>
    </body>
</html>

Upvotes: 0

Yanick Rochon
Yanick Rochon

Reputation: 53516

For those working in asynchronous environments, moment behaves unexpectedly when loading locales on demand.

Instead of

await import('moment/locale/en-ca');
moment.locale('en-ca');

reverse the order

moment.locale('en-ca');
await import('moment/locale/en-ca');

It seems like the locales are loaded into the current selected locale, overriding any previously set locale information. So switching the locale first, then loading the locale information does not cause this issue.

Upvotes: 1

Mussa Charles
Mussa Charles

Reputation: 4412

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")

Upvotes: 6

stackdave
stackdave

Reputation: 7054

end 2017 / 2018: the anothers answers have too much old code to edit, so here my alternative clean answer:

with require

let moment = require('moment');
require('moment/locale/fr.js');
// or if you want to include all locales:
require("moment/min/locales.min");

with imports

import moment from 'moment';
import 'moment/locale/fr';
// or if you want to include all locales:
require("moment/min/locales.min");

Use:

moment.locale('fr');
moment().format('D MMM YY');  // Correct, set default global format 
// moment.locale('fr').format('D MMM YY') //Wrong old versions for global default format

with timezone

*require:

require('moment-range');
require('moment-timezone');

*import:

import 'moment-range';
import 'moment-timezone';

use zones:

const newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
const losAngeles = newYork.clone().tz("America/Los_Angeles");
const london     = newYork.clone().tz("Europe/London");

function to format date

const ISOtoDate = function (dateString, format='') {

 // if date is not string use conversion:
 // value.toLocaleDateString() +' '+ value.toLocaleTimeString();

  if ( !dateString ) {
    return '';
  }

  if (format ) {
    return moment(dateString).format(format);
  } else  {
    return moment(dateString);  // It will use default global format
  }  
};

Upvotes: 19

kalley
kalley

Reputation: 18462

You need moment.lang (WARNING: lang() is deprecated since moment 2.8.0, use locale() instead):

moment.lang("de").format('LLL');

http://momentjs.com/docs/#/i18n/


As of v2.8.1, moment.locale('de') sets the localization, but does not return a moment. Some examples:

var march = moment('2017-03')
console.log(march.format('MMMM')) // 'March'

moment.locale('de') // returns the new locale, in this case 'de'
console.log(march.format('MMMM')) // 'March' still, since the instance was before the locale was set

var deMarch = moment('2017-03')
console.log(deMarch.format('MMMM')) // 'März'

// You can, however, change just the locale of a specific moment
march.locale('es')
console.log(march.format('MMMM')) // 'Marzo'

In summation, calling locale on the global moment sets the locale for all future moment instances, but does not return an instance of moment. Calling locale on an instance, sets it for that instance AND returns that instance.

Also, as Shiv said in the comments, make sure you use "moment-with-locales.min.js" and not "moment.min.js", otherwise it won't work.

Upvotes: 431

WesternGun
WesternGun

Reputation: 12728

For me, there are some changes to make(ver. 2.20)

  1. You set locale with moment.locale('de'), and you create a new object representing the date of now by moment() (note the parenthesis) and then format('LLL') it. The parenthesis is important.

So that means:

moment.locale('de');
var now = moment();
now.format('LLL');
  1. Also, remember to use moment-with-locale.js. The file contains all locale info and has a larger file size. Download the locale folder is not enough. If necessary, change the name to be moment.js. Django just refuses to load moment-with-locale.js in my case.

EDIT: It turned out that renaming the file is not necessary. I just forgot to invoke it in the page so Django does not think loading it is necessary, so my fault.

Upvotes: 3

apadana
apadana

Reputation: 14620

With moment 2.18.1 and onward:

  moment.locale("de");
  var m = moment().format("LLL")

Upvotes: 7

Claudio Scheuermann
Claudio Scheuermann

Reputation: 91

work fine like that: return moment(status.created_at).locale('es').fromNow();

Upvotes: 4

Anil Nankar
Anil Nankar

Reputation: 41

Change the moment js language as per Version

Version: 2.8+

moment.locale('hi');

Version: 2.5.1

moment.lang('hi');

Upvotes: 4

Dmitry
Dmitry

Reputation: 737

I'm using angular2-moment, but usage must be similar.

import { MomentModule } from "angular2-moment";
import moment = require("moment");

export class AppModule {

  constructor() {
    moment.locale('ru');
  }
}

Upvotes: 3

GameScripting
GameScripting

Reputation: 16992

As I was using webpack with gulp and friends (this generator set up everything for me) I had to make a change to the bower.json file. I had to override the default import for the moment package and select the file that comes with all the languages:

"overrides": {
  "moment": {
    "main": [
        "min/moment-with-locales.min.js"
    ]
  }
}

This is my full bower.json file:

{
  "name": "html5",
  "version": "0.0.0",
  "dependencies": {
    "angular-animate": "~1.4.2",
    "angular-cookies": "~1.4.2",
    "angular-touch": "~1.4.2",
    "angular-sanitize": "~1.4.2",
    "angular-messages": "~1.4.2",
    "angular-ui-router": "~0.2.15",
    "bootstrap-sass": "~3.3.5",
    "angular-bootstrap": "~0.13.4",
    "malarkey": "yuanqing/malarkey#~1.3.1",
    "angular-toastr": "~1.5.0",
    "moment": "~2.10.6",
    "animate.css": "~3.4.0",
    "angular": "~1.4.2",
    "lodash": "^4.13.1",
    "angular-moment": "^0.10.3",
    "angularLocalStorage": "ngStorage#^0.3.2",
    "ngstorage": "^0.3.10"
  },
  "devDependencies": {
    "angular-mocks": "~1.4.2"
  },
  "overrides": {
    "bootstrap-sass": {
      "main": [
        "assets/stylesheets/_bootstrap.scss",
        "assets/fonts/bootstrap/glyphicons-halflings-regular.eot",
        "assets/fonts/bootstrap/glyphicons-halflings-regular.svg",
        "assets/fonts/bootstrap/glyphicons-halflings-regular.ttf",
        "assets/fonts/bootstrap/glyphicons-halflings-regular.woff",
        "assets/fonts/bootstrap/glyphicons-halflings-regular.woff2"
      ]
    },
    "moment": {
      "main": [
          "min/moment-with-locales.min.js"
      ]
    }
  },
  "resolutions": {
    "angular": "~1.4.2"
  }
}

Upvotes: 3

Ram Pukar
Ram Pukar

Reputation: 1621

<!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

Upvotes: 3

mwarren
mwarren

Reputation: 2469

FOR METEOR USERS:

moment locales are not installed by default in meteor, you only get the 'en' locale with the default installation.

So you use the code as shown correctly in other answers:

moment.locale('it').format('LLL');

but it will remain in english until you install the locale you need.

There is a nice, clean way of adding individual locales for moment in meteor (supplied by rzymek).

Install the moment package in the usual meteor way with:

meteor add rzymek:moment

Then just add the locales that you need, e.g. for italian:

meteor add rzymek:moment-locale-it

Or if you really want to add all available locales (adds about 30k to your page):

meteor add rzymek:moment-locales

Upvotes: 7

Francisco Costa
Francisco Costa

Reputation: 7123

for momentjs 2.12+, do the following:

moment.updateLocale('de');

Also note that you must use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale.

Upvotes: 4

Rob Jens
Rob Jens

Reputation: 624

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).

Upvotes: 1

Smart Coder
Smart Coder

Reputation: 1738

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.

Upvotes: 15

Stephan K.
Stephan K.

Reputation: 15702

Fastest method: Install with Bower

I just installed moment with bower and linked de.js as javascript resource in my html project.

bower install moment --save

You can also manually download the moment.js and de.js.

Link 'de.js' in your project

Linking the de.js in my main project file automatically changed the locale for all accesses to the moment class and its methods.

There will be no need anymore to do a moment.locale("de"). or moment.lang("de"). in the source code.

Just link your desired locale like this:

<script src="/bower_components/moment/moment.js"></script>
<script src="/bower_components/moment/locale/de.js"></script>

Or you can link the libraries without the bower_components path, if you downloaded moment.js 1990ies-style via right-click, which still works fine in most scenarios.

Upvotes: 58

Nashenas
Nashenas

Reputation: 1701

With momentjs 2.8+, do the following:

moment.locale("de").format('LLL');

http://momentjs.com/docs/#/i18n/

Upvotes: 44

Related Questions