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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With