解析日期字符串在特定的语言环境(不是时区!) [英] Parse a date string in a specific locale (not timezone!)
本文介绍了解析日期字符串在特定的语言环境(不是时区!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用MomentJS,如有必要,我可以使用.locale
(或在较早版本中为.lang
)在特定时刻实例(而不是全局)上设置区域设置.我如何使用除全局语言环境以外的特定语言环境来解析字符串?由于moment
函数本身就是我们用于解析的东西,并且似乎没有.set
变体可以进行完整解析?
With MomentJS, if necessary I can set a locale on a specific moment instance (rather than globally) using .locale
(or .lang
in older versions). How can I parse a string using a specific locale other than the global one? Since the moment
function itself is what we use for parsing, and there doesn't seem to be a .set
variant that does full parsing?
例如:
// Assume the default locale is 'en' (just in case, I'll set it for the snippet)
moment.locale('en');
// I have this string that's in the French locale
var str = "30 Avril 2015";
// Parsing it fails
var m = moment(str, "DD MMMM YYYY");
snippet.log(m.format("YYYY-MM-DD")); // "Invalid Date"
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
推荐答案
从版本2.0.0
开始,可以将语言环境键作为第三个参数传递给moment()
和moment.utc()
As of version 2.0.0
, a locale key can be passed as the third parameter to moment()
and moment.utc()
// Assume the default locale is 'en' (just in case, I'll set it for the snippet)
moment.locale('en');
// I have this string that's in the French locale
var str = "30 Avril 2015";
// Parse it in 'fr'
var m = moment(str, "DD MMMM YYYY", "fr");
// Check result:
snippet.log(m.format("YYYY-MM-DD -- MMMM"));
// Check global locale
var locale = moment()._locale._abbr;
snippet.log('Locale : ' + locale);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
这篇关于解析日期字符串在特定的语言环境(不是时区!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文