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

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

它会产生NaN。

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

这甚至不是反应。

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

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

这怎么可能呢?


当前回答

在2.18.1秒之后:

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

其他回答

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

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

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

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

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

最快的方法:使用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.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
  }  
};