分析特定区域设置(而不是时区!)中的日期字符串
Parse a date string in a specific locale (not timezone!)
使用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>
相关文章:
- 分析特定区域设置(而不是时区!)中的日期字符串
- 如何将 UTC 日期时间(字符串)转换为访问者时区
- 测试字符串在 javascript 中是否具有时区
- 转换一个时间(字符串),例如1:00 IST到另一个时区(比如PST)
- 如何将UTC时间字符串转换为本地时区中正确的moment.js对象
- 在 JavaScript 中给定时区字符串的情况下计算 UTC 偏移量
- 在 JavaScript 中获取另一个时区的时区偏移量,而无需使用字符串
- 如何在 Javascript 中获取浏览器的时区字符串
- 使用时刻时区的客户端上的时区字符串
- 分析具有不同时区的字符串日期
- 将日期从带有偏移量的字符串转换为不同的时区
- 如何将“字符串”转换为“没有时区的时间戳”
- 由于时区的原因,字符串的新日期显示为前一天
- JavaScript在不更改时区的情况下从字符串创建新日期
- 字符串中的Firefox new Date()构造本地时区的时间
- 如何查找时区字符串
- 从JavaScriptDate对象中提取日期字符串,而不应用时区
- 如何从javascript日期对象中获取时区字符串
- 使用正则表达式,Javascript中还有其他方法从具有时区的字符串中提取日期吗?
- 在javascript中读取具有不同时区的日期字符串