how do I change the language of moment.js

2019-01-10 08:29发布

问题:

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

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

is giving NAN, did not work.

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

not reacting even, did not work as well.

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

no change, giving still English, did not work as well.

how is this possible?

回答1:

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 moments, but does not return an instance of moment. Calling locale on an instance, sets is for that instance AND returns that instance.



回答2:

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.



回答3:

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


回答4:

With momentjs 2.8+, do the following:

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

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



回答5:

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.



回答6:

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


回答7:

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

with imports

import moment from 'moment';
import 'moment/locale/fr';

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


回答8:

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



回答9:

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


回答10:

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


回答11:

Change the moment js language as per Version

Version: 2.8+

moment.locale('hi');

Version: 2.5.1

moment.lang('hi');



回答12:

With moment 2.18.1 and onward:

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


回答13:

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.



回答14:

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.



回答15:

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



回答16:

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