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

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

它会产生NaN。

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

这甚至不是反应。

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

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

这怎么可能呢?


当前回答

最快的方法:使用Bower安装

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

凉亭安装时刻—保存

您也可以手动下载moment.js和de.js。

在项目中链接“de.js”

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

不再需要执行moment.locale("de")。或 moment.lang(“德”)。在源代码中。

只需像这样链接你想要的地区:

<script src="/bower_components/moment/moment.js"></script>
<script src="/bower_components/moment/locale/de.js"></script>

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

其他回答

根据版本更改moment js语言

版本:2 + 8。

moment.locale('嗨');

版本:2.5.1

moment.lang('嗨');

我还必须导入语言:

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

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

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

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

与要求

let moment = require('moment');
require('moment/locale/fr.js');
// or if you want to include all locales:
require("moment/min/locales.min");

与进口

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

和时区

*要求:

require('moment-range');
require('moment-timezone');

*进口:

import 'moment-range';
import 'moment-timezone';

使用区域:

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

格式化日期的函数

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

这是通过自动检测当前用户位置来工作的。

import moment from "moment/min/moment-with-locales";

// Then use it as you always do. 
moment(yourDate).format("MMMM Do YYYY, h:mm a")

流星用户:

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