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

问题描述:

moment().format()创建根据moment().isValid()Moment.js - moment().format()创建无效日期?

这里是无效的日期是例如:

> 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")未创建严格解析有效的日期?

+0

请把 “moment.locale( '德');” –

+0

即使我删除月份的时间段,它仍然返回错误。 https://jsfiddle.net/f0pa2pb1/ – James

回答这个问题,以防其他人面临同样的问题。

这是由于一个问题与moment.js2.8.1不正确周期解析定制的短月份名称。此问题已在更新版本2.14.1中解决。

这里是产生在2.8.1不同的结果和2.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

我认为这是因为"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