Yang Wang
Yang Wang

Reputation: 415

moment.js change locale not working

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.

Upvotes: 28

Views: 51336

Answers (6)

Reactjs 18.2.0 Moment 2.30.1

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

let now = moment();
console.log(now.format('LLLL'));

Upvotes: 0

Gabriel Aguirre
Gabriel Aguirre

Reputation: 659

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

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

reference

Upvotes: 5

Dhaval Parmar
Dhaval Parmar

Reputation: 261

I think if you do

import 'moment/min/locales'

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

Upvotes: 2

batatop
batatop

Reputation: 1059

I found the solution here: https://stackoverflow.com/a/55334751/8318855

You should use the moment.updateLocale function

Upvotes: 0

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';

Upvotes: 43

searlea
searlea

Reputation: 8378

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

Upvotes: 79

Related Questions