javascript 如何更改 moment.js 的语言?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17493309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:31:13  来源:igfitidea点击:

How do I change the language of moment.js?

javascriptmomentjs

提问by doniyor

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:

我正在尝试更改由 moment.js 设置的日期的语言。默认是英语,但是我想设置德语。这些是我尝试过的:

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

It's giving NaN.

它给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?

这怎么可能?

回答by kalley

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

您需要 moment.lang (警告lang()自 moment 起已弃用2.8.0,请locale()改用):

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

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

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



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

从 v2.8.1 开始,moment.locale('de')设置本地化,但不返回moment. 一些例子:

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 localeon the global momentsets the locale for all future momentinstances, but does not return an instance of moment. Calling localeon an instance, sets it for that instance AND returns that instance.

总而言之,调用locale全局moment设置为所有未来moment实例设置语言环境,但不返回 的实例moment。调用locale一个实例,为该实例设置它并返回该实例。

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.

此外,正如 Shiv 在评论中所说,请确保您使用“moment-with-locales.min.js”而不是“moment.min.js”,否则它将无法工作。

回答by Agu Dondo

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

回答by stevek

Fastest method: Install with Bower

最快的方法:使用 Bower 安装

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

我刚刚用 bower 安装了 moment 并de.js在我的 html 项目中链接为 javascript 资源。

bower install moment --save

bower install moment --save

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

您也可以手动下载moment.jsde.js

Link 'de.js' in your project

在您的项目中链接“de.js”

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

链接de.js我的主项目文件中的 自动更改了对 moment 类及其方法的所有访问的语言环境。

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

将有 没有必要再去做一个moment.locale("de").或者 moment.lang("de").源代码。

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_componentspath, if you downloaded moment.js 1990ies-style via right-click, which still works fine in most scenarios.

或者bower_components,如果您通过右键单击下载 moment.js 1990ies-style,则可以在没有路径的情况下链接库,这在大多数情况下仍然可以正常工作。

回答by Nashenas

With momentjs 2.8+, do the following:

使用 momentjs 2.8+,执行以下操作:

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

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

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

回答by Smart Coder

You'd need to add moment.lang(navigator.language)in your script.

您需要添加moment.lang(navigator.language)脚本。

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.

并且还必须添加要显示的每个国家/地区语言环境:例如对于 GB 或 FR,您需要在 moment.js 库中添加该语言环境格式。此类格式的示例可在 momentjs 文档中找到。如果你不在 moment.js 中添加这种格式,那么它总是会选择美国语言环境,因为这是我目前看到的唯一一种。

回答by stackdave

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

2017/2018 年底:其他答案有太多旧代码需要编辑,所以这里是我的替代答案:

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

回答by mwarren

FOR METEOR USERS:

对于流星用户:

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

在meteor 中默认没有安装moment语言环境,您只能通过默认安装获得“en”语言环境。

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 momentin meteor (supplied by rzymek).

有一种不错的、干净的方式可以为moment中的moment添加单个语言环境(由rzymek提供)。

Install the momentpackage in the usual meteor way with:

以通常的流星方式安装moment包:

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

或者,如果您真的想添加所有可用的语言环境(向您的页面添加大约 30k):

meteor add rzymek:moment-locales

回答by apadana

With moment 2.18.1 and onward:

随着时刻 2.18.1 及以后:

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

回答by Ram Pukar

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

演示

回答by GameScripting

As I was using webpack with gulp and friends (this generatorset 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:

当我与 gulp 和朋友一起使用 webpack 时(这个生成器为我设置了一切),我不得不对 bower.json 文件进行更改。我必须覆盖 moment 包的默认导入并选择所有语言附带的文件:

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

This is my full bower.json file:

这是我的完整 bower.json 文件:

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