moment.locale() "fr-6ren">
gpt4 book ai didi

javascript - Moment.js - moment().format() 创建无效日期?

转载 作者:行者123 更新时间:2023-11-28 05:44:29 27 4
gpt4 key购买 nike

moment().format() 根据 moment().isValid() 创建无效日期

示例如下:

> moment.version
"2.14.1"
> moment.locale()
"fr"
> moment().format("ll")
"29 juill. 2016"
> moment("29 juill. 2016", "ll", true).isValid()
false

但是,如果我删除它起作用的月份中的期间:

> moment("29 juill 2016", "ll", true).isValid()
true

或者,如果我禁用严格解析(删除第三个参数),它会起作用:

> moment("29 juill. 2016", "ll").isValid()
true

这是为什么呢?为什么 moment().format("ll") 不创建经过严格解析的有效日期?

最佳答案

我自己回答这个问题,以防其他人遇到同样的问题。

这是由于 moment.js 版本 2.8.1 存在问题,无法正确解析带有句点的自定义短月份名称。此问题在更高版本 2.14.1 中得到解决。

以下示例在 2.8.12.14.1 中产生不同的结果

moment.locale("fr", {
monthsShort: [
"janv.",
"févr.",
"mars",
"avr.",
"Mai",
"juin",
"juilltest.",
"août",
"sept.",
"oct.",
"nov.",
"déc."
],
monthsParseExact: true,
longDateFormat: {
LL: "DD MMM YYYY",
ll: "DD MMM YYYY"
},

});
console.log(moment.version);
moment.locale('fr');
console.log(moment.locale());
var testDate = '29 juilltest. 2016'; // month name with period in it that matches the custom short name given above
console.log(moment(testDate, "LL", true).isValid());
console.log(moment(testDate, "ll", true).isValid());
console.log(moment.localeData("fr"));

版本 2.8.1: https://jsfiddle.net/3do4ubsj/

2.8.1
fr
false
false

版本 2.14.1: https://jsfiddle.net/pkhcaqmy/

2.14.1
fr
true
true

修复它的提交:https://github.com/moment/moment/commit/fc5a352e9ca30e32a96875810604ad981d1442c3

moment.js 存储库中的相关问题:https://github.com/moment/moment/issues/3126

关于javascript - Moment.js - moment().format() 创建无效日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38651796/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com