我正在尝试更改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路径的情况下链接库,这在大多数情况下仍然可以正常工作。

其他回答

对于momentjs 2.12+,执行以下操作:

moment.updateLocale('de');

还要注意,你必须使用moment。updateLocale(localeName, config)来更改现有的语言环境。moment.defineLocale(localeName, config)应该只用于创建一个新的区域设置。

你需要时间。lang(警告:lang()自2.8.0时刻起已弃用,请使用locale()代替):

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

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


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

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'

总而言之,在全局moment上调用locale将为所有未来moment实例设置locale,但不会返回moment实例。在实例上调用locale,为该实例设置它并返回该实例。

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

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

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

对我来说,有一些改变要做。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不认为加载它是必要的,这是我的错。

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

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

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