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

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

它会产生NaN。

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

这甚至不是反应。

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

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

这怎么可能呢?


当前回答

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

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

其他回答

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

对我来说,有一些改变要做。2.20)

使用moment.locale('de')设置locale,然后创建一个新对象,用moment()表示现在的日期(注意括号),然后格式化('LLL')它。括号很重要。

这意味着:

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

另外,记得使用moment-with-locale.js。该文件包含所有语言环境信息,文件大小较大。下载locale文件夹是不够的。如有必要,将名称改为moment.js。Django只是拒绝加载moment-with-locale.js。

编辑: 结果证明,重命名文件是不必要的。我只是忘记在页面中调用它,所以Django不认为加载它是必要的,这是我的错。

要使用moment(2.8.0之后的版本)更改区域设置,请执行以下步骤。

在index.html中按如下方式加载moment语言环境文件 < script src = " . . / node_modules / /地区/ it.js”> > < /脚本 根据需要设置locale - moment.locale('it'); moment。locale()会返回it 你可以在任何语言中使用moment,比如JavaScript、Angular、node等等。

在2.18.1秒之后:

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

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

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

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