How do I change the language of moment.js?

JavascriptMomentjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

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.

Solution 4 - Javascript

With momentjs 2.8+, do the following:

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

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

Solution 5 - Javascript

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
  }  
};

Solution 6 - Javascript

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.

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

With moment 2.18.1 and onward:

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

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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');
  }
}

Solution 14 - Javascript

Change the moment js language as per Version

Version: 2.8+

moment.locale('hi');

Version: 2.5.1

moment.lang('hi');

Solution 15 - Javascript

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

Solution 16 - Javascript

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

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

Solution 17 - Javascript

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

Solution 18 - Javascript

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

Solution 19 - Javascript

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

Solution 20 - Javascript

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.

Solution 21 - Javascript

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>

Solution 22 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondoniyorView Question on Stackoverflow
Solution 1 - JavascriptkalleyView Answer on Stackoverflow
Solution 2 - JavascriptAgu DondoView Answer on Stackoverflow
Solution 3 - Javascriptstevek-proView Answer on Stackoverflow
Solution 4 - JavascriptNashenasView Answer on Stackoverflow
Solution 5 - JavascriptstackdaveView Answer on Stackoverflow
Solution 6 - JavascriptSmart CoderView Answer on Stackoverflow
Solution 7 - JavascriptAlan P.View Answer on Stackoverflow
Solution 8 - JavascriptmwarrenView Answer on Stackoverflow
Solution 9 - JavascriptapadanaView Answer on Stackoverflow
Solution 10 - JavascriptFrancisco CostaView Answer on Stackoverflow
Solution 11 - JavascriptRam PukarView Answer on Stackoverflow
Solution 12 - JavascriptGameScriptingView Answer on Stackoverflow
Solution 13 - JavascriptDmitryView Answer on Stackoverflow
Solution 14 - JavascriptAnil NankarView Answer on Stackoverflow
Solution 15 - JavascriptClaudio ScheuermannView Answer on Stackoverflow
Solution 16 - JavascriptWesternGunView Answer on Stackoverflow
Solution 17 - JavascriptMussa CharlesView Answer on Stackoverflow
Solution 18 - JavascriptTahaView Answer on Stackoverflow
Solution 19 - JavascriptRob JensView Answer on Stackoverflow
Solution 20 - JavascriptYanick RochonView Answer on Stackoverflow
Solution 21 - JavascriptAshik MahmudView Answer on Stackoverflow
Solution 22 - JavascriptBhanu pratapView Answer on Stackoverflow