Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native moment.locale does not work

I am working with React Native version 0.45.1 and with moment version 2.18.1.

I am trying to change the date according to the device local, but I always get the date in 'en-Us' locale. I can't import all of the locales as I saw in some solutions since I don't know the device locale in advance. (for example: https://github.com/moment/moment/issues/2962)

any other options?

like image 397
b-asaf Avatar asked Jul 23 '17 11:07

b-asaf


2 Answers

I can't import all of the locales as I saw in some solutions since I don't know the device locale in advance.

Actually, you can import all of the locales in moment like this (moment-with-locales is mentioned right there on the homepage):

import moment from 'moment/min/moment-with-locales'
// Or if you are using require instead:
var moment = require('moment/min/moment-with-locales')

Then you should be able to get your device locale with whatever module/method you prefer (in my example, I'll be using Expo) and change the moment locale to it. For example:

var deviceLocale = await Expo.Util.getCurrentLocaleAsync()
moment.locale(deviceLocale)

I won't say that importing everything is the best method for handling this as moment-with-locales is larger than just moment, but it does what you want it to accomplish. You can also go the route of just importing the locales you support as mentioned in that Github comment I linked to.

like image 58
Michael Cheng Avatar answered Sep 28 '22 03:09

Michael Cheng


Instead of importing locale by locale, I'm using this solution to set the locale globally:

import { getDeviceLocale } from "react-native-device-info";
import moment from "moment";
import "moment/min/locales";

const deviceLocale = getDeviceLocale();

moment.locale(deviceLocale); //set your locale (eg: fr)
moment(1316116057189).fromNow(); // il y a 7 ans

Sharing this to those who need it

like image 37
Annie Tan Avatar answered Sep 28 '22 03:09

Annie Tan