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

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

它会产生NaN。

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

这甚至不是反应。

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

没有变化:这仍然是用英语生成的结果。

这怎么可能呢?


当前回答

流星用户:

Moment locale没有在meteor中默认安装,您只能在默认安装中获得'en' locale。

所以你使用的代码显示正确的其他答案:

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

但在安装所需的区域设置之前,它将保持英文。

有一种很好的、干净的方法可以为meteor中的moment添加单独的locale(由rzymek提供)。

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

meteor add rzymek:moment

然后添加你需要的语言环境,例如意大利语:

meteor add rzymek:moment-locale-it

或者如果你真的想添加所有可用的地区(添加大约30k到你的页面):

meteor add rzymek:moment-locales

其他回答

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

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

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

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

我们可以使用moment.locale()方法来传递您自己的语言ex。我使用window.navigator.language (ex.en- us)在运行时传递lange。

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

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

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

我还必须导入语言:

import moment from 'moment'
import 'moment/locale/es'  // without this line it didn't work
moment.locale('es')

然后像平常一样利用这一刻

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