如何在momentJS中更改语言环境?

时间:2018-01-30 20:36:48

标签: react-native momentjs

这就是我所拥有的,但它不起作用。

import moment from 'moment'
import 'moment/min/moment-with-locales'
import 'moment-duration-format' // used by moment

componentDidMount () {
  console.log(moment.locale())
  console.log(moment.locale('zh-cn')) 
  console.log(moment.locale()) 
}

控制台日志输出: en,en,en

预期的控制台日志输出:en,zh-cn,zh-cn

当我尝试从'时刻改变导入时刻'从当地时间/分钟/时刻导入时刻'但它在这一行引发错误:

const total = moment.duration(this.props.stoveUsage.total, 'seconds').format('H:mm', { trim: false }) 

错误:momentWithLocales2.default.duration(...)。format不是函数

2 个答案:

答案 0 :(得分:6)

您需要做的就是导入要使用的语言环境。在我的示例中,我想确保所有日期都使用西班牙语,这就是我所做的:

import moment from 'moment';
import 'moment/locale/es';

然后在需要时执行以下操作:

moment.locale('es')
moment(date).format("DD - MMMM - YYYY"

输出将是:

19 - julio - 2018

我想您将必须在应用程序中导入所需数量的语言环境。

答案 1 :(得分:0)

只需添加到Nicoyuste的答案中,您就可以使用来动态导入

import(`moment/locale/${navigator.language.toLocaleLowerCase()}`).then();