KarloSpacapan
KarloSpacapan

Reputation: 373

Setting locale in moment.js not working despite using the locale file

There is a setLocale method in a dependency of a project, and I call this method from the project on locale change. However, the locale doesn't seem to change.

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

export const setLocale = locale => {
    console.log(`Locale to be set: ${locale}`)
    moment.locale(locale);
    console.log(moment.locale())
};

Output in console

I'm using moment-js v2.26.0in the dependency and 2.24.0 in the main project.

Same happens if I set locale explicitly.

However, changing the locale works in the main project works just fine.

Upvotes: 0

Views: 10901

Answers (2)

KarloSpacapan
KarloSpacapan

Reputation: 373

I fixed this issue by importing momentjs and locales in the following way:

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

From momentjs documentation

To save the step of loading individual locales (i.e. just load them all), import the moment/min/moment-with-locales module instead.

This of course doesn't explain why importing just one file fails.

Upvotes: 10

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

From official documentation

Note: There is a bug that prevents moment.locale from being loaded.

var moment = require('moment'); 
moment.locale('cs');
console.log(moment.locale()); // en 

use workaround below

var moment = require('moment'); 
require('moment/locale/cs');
console.log(moment.locale()); // cs

Upvotes: 1

Related Questions