Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment.js change locale not working

Tags:

momentjs

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.

like image 947
Yang Wang Avatar asked Apr 12 '18 04:04

Yang Wang


People also ask

How to change moment js locale?

You set locale with moment. locale('de') , and you create a new object representing the date of now by moment() (note the parenthesis) and then format('LLL') it. The parenthesis is important.

How do I change locale globally moments?

You can change moment locale globally like that: import moment from 'moment'; import localization from 'moment/locale/fr'; moment. locale('fr', localization);

Is Momentjs deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

How do I import a locale moment?

moment. Loading locales in NodeJS is super easy. If there is a locale file in moment/locale/ named after that key, import it first, then call moment. locale to load it. To save the step of loading individual locales (i.e. just load them all), import the moment/min/moment-with-locales module instead.


1 Answers

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
like image 154
searlea Avatar answered Sep 22 '22 23:09

searlea