2016-07-29 282 views
1

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

回答

0

回答這個問題,以防其他人面臨同樣的問題。

這是由於一個問題與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

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