分析特定区域设置(而不是时区!)中的日期字符串

Parse a date string in a specific locale (not timezone!)

本文关键字:时区 字符串 日期 区域 设置      更新时间:2023-09-26

使用MomentJS,如果需要,我可以使用.locale(或旧版本中的.lang)在特定时刻实例(而不是全局)上设置区域设置。如何使用全局语言环境以外的特定语言环境来解析字符串?既然moment函数本身就是我们用来解析的,而且似乎没有.set变体可以进行完全解析?

例如:

// 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()

// 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>