Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to change locale in momentJS in React Native? #4422

Closed
VanessaChu opened this issue Jan 30, 2018 · 28 comments
Closed

How to change locale in momentJS in React Native? #4422

VanessaChu opened this issue Jan 30, 2018 · 28 comments

Comments

@VanessaChu
Copy link

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

@VanessaChu VanessaChu changed the title How to change locale in momentJS? How to change locale in momentJS in React Native? Jan 30, 2018
@rudyryk
Copy link

rudyryk commented Feb 1, 2018

Confirming that, moment.locale('es') has no effect for me in React Native.

@rudyryk
Copy link

rudyryk commented Feb 1, 2018

import 'moment/min/moment-with-locales'

does the trick!

moment.locale('fr'); moment().format("ll");

results in "1 févr. 2018" as expected.

@benadamstyles
Copy link

If you don't want to use moment-with-locales, which loads all locale data, rolling back to moment v2.18 fixed this for me. There is definitely a bug with moment v2.20 and setting the locale in react native.

@msevestre
Copy link

@Leeds-eBooks Could you explain how you import moment? I rolled back to 2.18 and yet I need to import moment from moment-with-locales in to get local to work properly in react-native

Thanks

@benadamstyles
Copy link

benadamstyles commented Mar 20, 2018

@msevestre Yeah of course, although I think my solution may be out of date now, I made it work in my code and moved on, I think a later version of moment might have fixed it. Nevertheless, my fix is:

  • install https://github.com/tqc/moment.git#no-dynamic-import from git, instead of moment directly from npm
  • then:
import moment from 'moment'

import 'moment/src/locale/en-gb'
import 'moment/src/locale/es'
import 'moment/src/locale/fr'
import 'moment/src/locale/pl'
import 'moment/src/locale/pt'
// ...etc

// bonus trick!
import DeviceInfo from 'react-native-device-info'
const deviceLocale = DeviceInfo.getDeviceLocale()
moment.locale([deviceLocale, 'en'])

This is what I'm doing, and it's working for me, but as I say it may no longer be necessary.

@msevestre
Copy link

@Leeds-eBooks Awesome. Thanks for your quick feedback. Really helped

@marwahaha
Copy link
Member

@VanessaChu - do you still have a problem?

@jeffhtli
Copy link

This solution works for me

@MayeuldP
Copy link

Hey peoples, import 'moment/locale/fr'; works for me, but if I want to do a dynamical one, like not have to import all the exisiting languages, do you know any tricks to do something like import 'moment/locale/[variable]' where variable is the needed language ?
So that it works with every country... :/

@ichernev
Copy link
Contributor

I hope most discussion participants got their problems sorted out :) Thank you @Leeds-eBooks

For 3.x we might have more versions of moment with/without the dynamic import/es6 so this is less of an issue.

@stenrdj
Copy link

stenrdj commented Aug 30, 2018

Hello @MayeuldP ,
i don't know if you arrive to fix using variable languages of moments in Reactjs / ReactNative , but i want to share the solution it may help somebody .
you don't have to import culture by culture instead just add : import 'moment/min/locales' only and later you can set your moment.local('') with your favorite culture.

@KashifAhmed
Copy link

KashifAhmed commented Sep 27, 2018

I'm using v2.18 and this method works.

import moment from 'moment';
import momentFR from 'moment/src/locale/fr' 
moment.locale('fr',momentFR );

@fructurj
Copy link

Hi, @KashifAhmed In v.2.22.2 you should use moment.updateLocale('fr',momentFR)

Deprecation warning: use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info.

@RicardoBer
Copy link

RicardoBer commented Feb 11, 2019

Check this:

import moment from "moment";
import 'moment/min/locales'

This include all languajes configurations from moment, it's js, so no problem with size.

I had problem before when some one install the app with an mobile with different languaje.

From this you can set any locale defined by moment without any problem,

moment.locale('es');

Or using device locale without worries about it is out of your languajes specs as example from @benadamstyles

@euharrison
Copy link

In my case, import the locale wasn't enough, so I used the imported dictionary and remove the first character that is an underscore _

import moment from 'moment';
import momentPTBR from 'moment/src/locale/pt-br';

function prepareLocale(locale) {
  for (const key in locale) {
    if (locale.hasOwnProperty(key)) {
      // remove first character underscore fom key, i.e. '_calendar' => 'calendar'
      locale[key.substring(1)] = locale[key];
    }
  }
  return locale;
}

moment.defineLocale('pt-br', prepareLocale(momentPTBR));

@Asday
Copy link

Asday commented May 23, 2019

import 'moment/src/locale/en-gb' didn't work for me, but import 'moment/locale/en-gb' did.

  "dependencies": {
    "expo": "32.0.0",
    "moment": "2.24.0",
    "react": "16.5.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz"
  },

In the upper-most file in the tree, here's how my code looks:

import moment from 'moment'

import 'moment/locale/en-gb'

const momentLocale = moment.locale('en-gb')
if (momentLocale !== 'en-gb') {
  throw new Error(`Moment fell back to locale ${momentLocale}`)
}

export default () => null

@karthikeyan110798
Copy link

I'm using v2.18 and this method works.

import moment from 'moment';
import momentFR from 'moment/src/locale/fr' 
moment.locale('fr',momentFR );
``

could you please give some examples.
thanks a lot!

@thinklinux
Copy link

I changed my version from 2.24 to 2.18 and it works now. There is a bug somewhere after 2.20.

@juliovieceli
Copy link

its work for me

import moment from 'moment'
import 'moment/locale/pt-br'
moment.locale('pt-br')

@Asday
Copy link

Asday commented Mar 13, 2020

its work for me

import moment from 'moment'
import 'moment/locale/pt-br'
moment.locale('pt-br')

Make sure you're checking that what you get back from .locale() is what you set. It falls back silently.

@wmonecke
Copy link

wmonecke commented Mar 6, 2021

I don't understand how this is working for you guys.
For me, it is ONLY working on the initial view. If you go to another view moment default back to English.

In other words moment.locale() is setting the locale to the local instance of moment and NOT GLOBAL.

@Asday
Copy link

Asday commented Mar 6, 2021

Set it in your app root, not in a view. Mine is above the call to ReactDOM.render().

@wmonecke
Copy link

wmonecke commented Mar 6, 2021

@Asday

This is my index.js

import moment from 'moment'
import strings from './src/i18n/strings'
import 'moment/locale/fr';
import 'moment/locale/de';
import 'moment/locale/it';
import 'moment/locale/pt';
import 'moment/locale/es';
const deviceLanguage = strings.getInterfaceLanguage().split('-')[0].split('_')[0];
moment.locale([deviceLanguage, 'en'])

import 'react-native-gesture-handler';
import App from './src/App';
import { AppRegistry } from 'react-native';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);

"moment": "^2.29.1",

Works on the first view and when I navigate away it stops working.

If I refresh the simulator it works on all the app. But on my physical device, it just works only in the first view like mentioned above. This is so frustrating.

@Asday
Copy link

Asday commented Mar 6, 2021

Opened the project I've done this on to check, and I don't have an index. I let react-native take care of whatever it wants to in there, and set my locale in App.jsx.

What's the advantage of hand-rolling your own index? Is the react-native provided one doing something yours isn't?

@AmirDiafi
Copy link

this is what you look for:

import * as RNLocalize from 'react-native-localize'
const local = RNLocalize.getLocales()
const lanTag = local[0].languageTag.toLowerCase()
console.log(lanTag)
import moment from 'moment'
import 'moment/min/locales'
moment.locale(lanTag) //set moment local

@devpedroso
Copy link

devpedroso commented Sep 15, 2022

MUITO OBRIGADO MESMO <3

Voltei para a versão 2.18.0, importei dessa forma:

import moment from 'moment';
import 'moment/locale/pt-br';

FUNCIONOU!!!!!

@arbisyarifudin
Copy link

I use v2.29.4

import moment from 'moment'
import 'moment/dist/locale/id'
moment.locale('id')

and IT'S WORK!!

@samy-tcheik
Copy link

I use version v2.29.4
and this solution worked for me

import moment from 'moment'
import 'moment/min/locales*
moment.locale("ar")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests