我正在尝试更改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")
其他回答
我们可以使用moment.locale()方法来传递您自己的语言ex。我使用window.navigator.language (ex.en- us)在运行时传递lange。
const formatDate = date => moment(date).locale(window.navigator.language).format('LL')
最快的方法:使用Bower安装
我刚刚在我的html项目中安装了moment with bower和链接de.js作为javascript资源。
凉亭安装时刻—保存
您也可以手动下载moment.js和de.js。
在项目中链接“de.js”
在我的主项目文件中链接de.js会自动改变对moment类及其方法的所有访问的语言环境。
不再需要执行moment.locale("de")。或 moment.lang(“德”)。在源代码中。
只需像这样链接你想要的地区:
<script src="/bower_components/moment/moment.js"></script>
<script src="/bower_components/moment/locale/de.js"></script>
或者,如果您通过右键单击下载了moments .js 1990ies样式,则可以在没有bower_components路径的情况下链接库,这在大多数情况下仍然可以正常工作。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MomentJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript" src="moment.js"></script>
<script type="text/javascript" src="locale/ne.js"></script>
</head>
<body>
<script>
jQuery(document).ready(function($) {
moment.locale('en'); // default the locale to English
var localLocale = moment();
moment.locale('ne'); // change the global locale to Nepalese
var ne1 = localLocale.format('LLLL');
var ne2 = moment().format('LLLL');
$('.ne1').text(ne1);
$('.ne2').text(ne2);
});
</script>
<p class="ne1"></p>
<p class="ne2"></p>
</body>
</html>
Demo
这是通过自动检测当前用户位置来工作的。
import moment from "moment/min/moment-with-locales";
// Then use it as you always do.
moment(yourDate).format("MMMM Do YYYY, h:mm a")
对我来说,有一些改变要做。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不认为加载它是必要的,这是我的错。