如何更改 moment.js 的语言?

新手上路,请多包涵

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

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

它给了 NaN

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

这甚至没有反应。

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

没有变化:这仍然会产生英语结果。

这怎么可能?

原文由 doniyor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2k
2 个回答

您需要 moment.lang ( 警告lang() 自 moment 2.8.0 起已弃用,请改用 locale() ):

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

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


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

 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-locales.min.js”而不是“moment.min.js”,否则将无法正常工作。

原文由 kalley 发布,翻译遵循 CC BY-SA 4.0 许可协议

我还必须导入语言:

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

然后像往常一样使用 moment

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

原文由 Agu Dondo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题