moment.js 更改区域设置不起作用

问题描述 投票:0回答:6

我的项目是一个react项目。

我的网站是一个多语言网站,当我更改网络语言时。

moment.locale(lang)
不工作。

我的代码是:

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

无论我设置什么

lang
我检查
startDate.locale()
始终是
'en'
startDate.format('ll')
结果始终是英语。

momentjs
6个回答
73
投票

如果项目是使用 create-react-app 创建的,则可能会 默认排除

这现已记录在 create-react-app 故障排除指南的“Moment.js 语言环境丢失”部分中。

解决方案:除了“moment”之外还显式导入语言环境:

import moment from 'moment';
import 'moment/locale/fr';
import 'moment/locale/es';
// etc. as required

27
投票

根据这个github问题,从2022年左右开始,它必须像这样导入:

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

moment.locale('de');

如果这不起作用,请尝试以下更改:

import moment from 'moment/dist/moment';

1
投票

我想如果你这样做

import 'moment/min/locales'

而不是单独导入每个语言环境。 就我而言,它解决了我的问题


1
投票

对于像这样的 React Native 应用程序导入时刻解决了问题

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

参考


0
投票

我在这里找到了解决方案:https://stackoverflow.com/a/55334751/8318855

您应该使用

moment.updateLocale
功能


0
投票

Reactjs 18.2.0

从“时刻”导入时刻; 导入“时刻/语言环境/ru”;

让现在=时刻(); console.log(now.format('LLLL'));

© www.soinside.com 2019 - 2024. All rights reserved.