Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change locale in momentJS?

This is what I have but it does not work.

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()) 
}

console log outputs: en, en, en

expected console log output: en, zh-cn, zh-cn

When I tried changing import moment from 'moment' to import moment from 'moment/min/moment-with-locales' but it throws an error on this line:

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

error: momentWithLocales2.default.duration(...).format is not a function

like image 453
chubbychu Avatar asked Jan 30 '18 20:01

chubbychu


1 Answers

All you need to do is to import the locale you want to use. In my example, I wanted to make sure all the dates were in Spanish and this is what I did:

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

Then whenever you need it just do:

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

The output will be:

19 - julio - 2018

I guess you will have to import as many locales as you need in your application.

like image 53
Nicolas Yuste Avatar answered Sep 28 '22 02:09

Nicolas Yuste