使用MomentJS,如果需要,我可以使用.locale
(或旧版本中的.lang
)在特定时刻实例(而不是全局)设置区域设置。如何使用除全局区域之外的特定区域设置解析字符串?由于moment
函数本身就是我们用于解析的函数,并且似乎没有.set
变体进行完全解析?
E.g:
// 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>
答案 0 :(得分:6)
从版本2.0.0
开始,区域设置键可以作为第三个参数传递给moment()
和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);
&#13;
<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>
&#13;