我正在尝试更改moment.js设置的日期的语言。默认是英语,但我想设置德语。以下是我的尝试:
var now = moment().format("LLL").lang("de");
它会产生NaN。
var now = moment("de").format("LLL");
这甚至不是反应。
var now = moment().format("LLL", "de");
没有变化:这仍然是用英语生成的结果。
这怎么可能呢?
我正在尝试更改moment.js设置的日期的语言。默认是英语,但我想设置德语。以下是我的尝试:
var now = moment().format("LLL").lang("de");
它会产生NaN。
var now = moment("de").format("LLL");
这甚至不是反应。
var now = moment().format("LLL", "de");
没有变化:这仍然是用英语生成的结果。
这怎么可能呢?
当前回答
这是通过自动检测当前用户位置来工作的。
import moment from "moment/min/moment-with-locales";
// Then use it as you always do.
moment(yourDate).format("MMMM Do YYYY, h:mm a")
其他回答
经过一番挣扎后,这对我来说是有效的v2.26.0时刻:
import React from "react";
import moment from "moment";
import frLocale from "moment/locale/fr";
import esLocale from "moment/locale/es";
export default function App() {
moment.locale('fr', [frLocale, esLocale]) // can pass in 'en', 'fr', or 'es'
let x = moment("2020-01-01 00:00:01");
return (
<div className="App">
{x.format("LLL")}
<br />
{x.fromNow()}
</div>
);
}
你可以传入en fr es。如果需要另一种语言,则必须导入区域设置并将其添加到数组中。
如果你只需要支持一种语言,那就更简单了:
import React from "react";
import moment from "moment";
import "moment/locale/fr"; //always use French
export default function App() {
let x = moment("2020-01-01 00:00:01");
return (
<div className="App">
{x.format("LLL")}
<br />
{x.fromNow()}
</div>
);
}
——更新——
在一种情况下,像上面那样导入所有区域设置文件将使用最后导入的始终使用的区域设置(即。在上面的例子中是“es”),即使我把它设置为“fr”。似乎有效的解决方案是:
import moment from 'moment';
import 'moment/min/locales';
...
moment.locale('fr');
流星用户:
Moment locale没有在meteor中默认安装,您只能在默认安装中获得'en' locale。
所以你使用的代码显示正确的其他答案:
moment.locale('it').format('LLL');
但在安装所需的区域设置之前,它将保持英文。
有一种很好的、干净的方法可以为meteor中的moment添加单独的locale(由rzymek提供)。
以通常的流星方式安装moment包:
meteor add rzymek:moment
然后添加你需要的语言环境,例如意大利语:
meteor add rzymek:moment-locale-it
或者如果你真的想添加所有可用的地区(添加大约30k到你的页面):
meteor add rzymek:moment-locales
在2.18.1秒之后:
moment.locale("de");
var m = moment().format("LLL")
我不知道发生了什么变化,但像这样导入语言文件对我有用
import 'moment/src/locale/fr';
moment.locale('fr')
注意import语句中的src
对我来说,有一些改变要做。2.20)
使用moment.locale('de')设置locale,然后创建一个新对象,用moment()表示现在的日期(注意括号),然后格式化('LLL')它。括号很重要。
这意味着:
moment.locale('de');
var now = moment();
now.format('LLL');
另外,记得使用moment-with-locale.js。该文件包含所有语言环境信息,文件大小较大。下载locale文件夹是不够的。如有必要,将名称改为moment.js。Django只是拒绝加载moment-with-locale.js。
编辑: 结果证明,重命名文件是不必要的。我只是忘记在页面中调用它,所以Django不认为加载它是必要的,这是我的错。