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

时间:2016-07-29 06:20:30

标签: javascript momentjs

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

或者,如果我禁用严格解析(删除第3个参数),它可以工作:

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

这是为什么?为什么moment().format("ll")没有创建一个有严格解析的日期?

2 个答案:

答案 0 :(得分:0)

我认为这是因为"ll"不是有效的日期格式,如果您要运行时刻功能并要求时间戳(.valueOf),您将获得NaN

moment("29 juill 2016", "ll", true).valueOf()
// NaN

您需要为第二个参数提供有效的格式,日期字符串为"DD MMMM, YYYY"

另外,我认为您在juill中输了一个拼写错误,我认为它应该是juillet

moment.locale("fr")
// "fr"
 moment("29 july, 2016", "DD MMMM, YYYY", true).isValid()
// false
 moment("29 juillet, 2016", "DD MMMM, YYYY", true).isValid()
// true

答案 1 :(得分:0)

如果其他人面临同样的问题,请自行回答。

这是由于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 repo中的相关问题:https://github.com/moment/moment/issues/3126

相关问题