303

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
doniyor
  • 36,596
  • 57
  • 175
  • 260

24 Answers24

410

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.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
kalley
  • 18,072
  • 2
  • 39
  • 36
  • 1
    In the docs, you can create language specific instances of moment by doing that. If you format first, the language won't process. Alternatively, you could do something like `var deMoment = moment(); deMoment.lang('de')` and reuse `deMoment` instead of moment throughout your script. – kalley Jul 06 '13 at 16:49
  • 51
    If you use "moment.min.js" it won't work; you need "moment-with-locales.min.js" – Shiv Jan 23 '16 at 09:19
  • 3
    update: `Deprecation warning: moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages. Arguments: fr` – Abdelouahab Mar 04 '16 at 17:07
  • If you use browserify, according to the official docs, there is a bug that prevents locale form being loaded. Fortunately, a workaround is also provided, see: http://momentjs.com/docs/#/use-it/browserify/. I was stuck with this myself and it worked! – jotadepicas Mar 20 '16 at 17:29
  • 1
    with 2.12.0 I get `Uncaught TypeError: moment.locale(...).format is not a function(…)` – trushkevich Apr 06 '16 at 11:47
  • 1
    me too: moment.locale(...).format is not a function(…) – Predrag Stojadinović Sep 03 '16 at 13:37
  • this answer is wrong in 2017, look at @apadana answer – stackdave Nov 28 '17 at 07:46
  • 1
    Must include the locale files, otherwise it will not work.The locale files can use the cdn from here: https://cdnjs.com/libraries/moment.js – zeleven Dec 27 '17 at 09:21
  • 24
    you need to import the wanted language other wise this wont work: `import moment from 'moment'; import localization from 'moment/locale/de'` `moment().locale("de", localization).format('LLL')` – Blue Bot Sep 06 '18 at 08:10
  • 7
    import moment from 'moment/min/moment-with-locales'; – leojnxs Oct 29 '18 at 03:20
  • you can use this **'Moment.locale('tr')' ** in useeffect func and you must import this **moment/min/moment-with-locales** and where ever can call – cantaş Aug 04 '20 at 21:02
  • Then you need to import moment. `import * as moment from 'moment'` – David Jesus Sep 04 '20 at 20:09
  • hi, do this work also on hole application setting as in app.module.ts? thank you – vladanPro Jan 28 '21 at 15:37
  • Is there a less convoluted way of using locale than what @Abdelouahab suggested? That's the only way I got it to work but it looks like it could be easier. – 10110 Jun 02 '21 at 14:58
373

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())
Agu Dondo
  • 12,638
  • 7
  • 57
  • 68
  • 48
    Your answer more helpful than other because you've mentioned about `import 'moment/locale/es'` – Kas Elvirov Aug 08 '18 at 11:14
  • 7
    Yes this is the correct answer... thanks, I was pulling my hair out wondering why it wasn't working. But this is a real pain having to import for any language type that might be used. There has to be a better way. – Maniaque Sep 28 '18 at 15:28
  • 2
    according to the documentation if someone wants all the locales to be included then he/she can use this `require("moment/min/locales.min");` or using import `import 'moment/min/locales.min'` – kamran Jun 15 '20 at 09:49
  • how`moment/locale/es` can be used with i18next lib ? – Hamid Shoja Nov 19 '21 at 07:49
  • 1
    Use `import 'moment/min/locales';` for all the languages. – tharinduPro Feb 23 '23 at 04:06
57

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.

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147
  • 2
    This should be the correct answer. Just link the desired local with ``.It works for me right now. – mles Jan 15 '15 at 21:11
  • 8
    "There will be no need anymore to do a moment.locale("de"). or moment.lang("de"). in the source code.". I think this is still useful for dynamic apps that change the locale. Like you can theoretically change the locale in my app via a lang/country dropdown in my angular app and then moment should change formats dynamically which I would do I think with moment.locale($lang) – armyofda12mnkeys May 07 '15 at 15:32
  • Sure, but you still need to load the javascript file in your index.html in my tests. This is still an issue in May 2017, maybe moment should include this in their docs. – Stephan Kristyn Apr 26 '17 at 16:13
44

With momentjs 2.8+, do the following:

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

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

Nashenas
  • 1,651
  • 1
  • 21
  • 25
  • It *should* work; can you provide an example of where it doesn't work, also how are you using moment (did you install it via npm, etc)? – omninonsense May 11 '17 at 14:16
  • 4
    With recent moments (I tested in 2.18.1) use this: moment.locale("de"); var m = moment().format("LLL") – apadana Jul 21 '17 at 08:34
  • 1
    apadana is right: 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. Tested in 2.20. Also, remember to use `moment-with-locale.js` and if necessary, change the name to be `moment.js`. Django just refuse to load `moment-with-locale.js` in my case. – WesternGun Dec 21 '17 at 10:45
  • 1
    if this one is not working, try this one : `moment().locale('de').format('LLL');` – Anthony Kal Feb 01 '18 at 03:06
  • This one is coorect, just don't forget to import te locale you want to use (cfr. Agu Dondo's answer). – Jeroen Crevits Jul 22 '19 at 10:05
23

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');
Alan P.
  • 2,898
  • 6
  • 28
  • 52
19

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
  }  
};
stackdave
  • 6,655
  • 9
  • 37
  • 56
  • 1
    The only thing worked for me was change moment import to: `import moment from 'moment/min/moment-with-locales';` – leojnxs Oct 29 '18 at 03:19
  • @leojnxs yes, if you want to include all locales, but it's possible to work only with one or more specific locales doing a import for every language – stackdave Oct 09 '19 at 03:03
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.

Smart Coder
  • 1,435
  • 19
  • 19
7

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
mwarren
  • 2,409
  • 1
  • 22
  • 28
  • @AntonAL Good thing you sent me your comment, I've just noticed that the question wasn't actually for meteor. However my answer's pretty useful I reckon. I've edited my answer to reflect this. – mwarren Mar 16 '16 at 11:03
  • Thanks! Added `rzymek:moment-locale-de` and it worked :) – nooitaf Jul 10 '17 at 11:47
7

With moment 2.18.1 and onward:

  moment.locale("de");
  var m = moment().format("LLL")
apadana
  • 13,456
  • 15
  • 82
  • 98
5

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

Taha
  • 434
  • 5
  • 12
4

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

  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Badacadabra Jun 04 '17 at 12:08
4

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")
Mussa Charles
  • 4,014
  • 2
  • 29
  • 24
3

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.

Francisco Costa
  • 6,713
  • 5
  • 34
  • 43
3
<!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

Ram Pukar
  • 1,583
  • 15
  • 17
3

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"
  }
}
GameScripting
  • 16,092
  • 13
  • 59
  • 98
  • After this, you still have to declare/set the moment locale before outputting a date, right? – NikZ Feb 01 '17 at 13:26
  • Of course :) This just ensures you have the translated phrases available so you can switch to another language (on the fly) – GameScripting Feb 01 '17 at 21:06
3

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');
  }
}
Dmitry
  • 727
  • 1
  • 8
  • 34
3

Change the moment js language as per Version

Version: 2.8+

moment.locale('hi');

Version: 2.5.1

moment.lang('hi');

3

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.

WesternGun
  • 11,303
  • 6
  • 88
  • 157
1

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

Rob Jens
  • 584
  • 6
  • 8
1

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.

Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214
1

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.

Bhanu pratap
  • 81
  • 1
  • 3
0

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>
Ashik Mahmud
  • 117
  • 3
0

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')
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
0

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