moment.js change locale not working
Asked Answered
C

6

26

My project is a react project.

My website is a mutilanguage website, when I change the web language. moment.locale(lang) not working.

My code is:

const startDate = moment.utc(start).locale(lang);
const endDate = moment.utc(end).locale(lang);

whatever I set lang I check the startDate.locale() always is 'en' startDate.format('ll') result always is English.

Chelyabinsk answered 12/4, 2018 at 4:54 Comment(3)
Possible duplicate of how do I change the language of moment.jsWillardwillcox
same issue here did you got the fix yet?Geometrize
Possible duplicate of How to change locale in momentJS?Herder
B
77

If the project was created using create-react-app, moment locales were probably excluded by default.

This is now documented in the "Moment.js locales are missing" section of create-react-app's troubleshooting guide.

Solution: explicitly import locales in addition to 'moment':

import moment from 'moment';
import 'moment/locale/fr';
import 'moment/locale/es';
// etc. as required
Borneol answered 17/5, 2019 at 7:27 Comment(2)
I had to add "/dist" to the import: import 'moment/dist/locale/es'Wattmeter
@HectorToro you helped me thanksAngieangil
K
33

According to this github issue, from 2022 on or so, it has to be imported like so:

import moment from 'moment';
import 'moment/dist/locale/de';

moment.locale('de');

if this doesn't work, try this change:

import moment from 'moment/dist/moment';
Katrinakatrine answered 10/5, 2022 at 12:57 Comment(2)
thanks, i used import 'moment/locale/fr'; or import 'moment/lib/locale/fr'; but not working import 'moment/dist/locale/fr'; workNidifugous
Bloody christ thanks for this. Nothing worked, this did.Rapp
K
4

For a react native app importing moment like this fixed the issue

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

reference

Kilogram answered 29/5, 2023 at 22:4 Comment(1)
I was looking for the exact solution for my React project, your suggestion worked great. Thank you very much.Na
P
1

I think if you do

import 'moment/min/locales'

Instead of individual import of each locale. In my case it resolve my problem

Premundane answered 12/8, 2022 at 6:42 Comment(1)
Got them to bundle for me.Baum
A
0

I found the solution here: https://mcmap.net/q/535368/-how-to-set-language-globally-for-moment-js

You should use the moment.updateLocale function

Anticatalyst answered 13/5, 2022 at 11:36 Comment(0)
A
0

Reactjs 18.2.0 Moment 2.30.1

import moment from "moment";
import 'moment/locale/ru';

let now = moment();
console.log(now.format('LLLL'));
Alternate answered 1/3 at 11:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.