2017-07-03 81 views
1

當我將年,月,日作爲字符串傳遞到moment.js日期構造函數以獲取該月的最後一天時,它返回「Invalid date」三月和八月:moment.js返回三月和八月最後一天的「無效日期」

moment(["2022","0","31"]).toISOString() 
"2022-01-31T06:00:00.000Z" 
moment(["2022","1","28"]).toISOString() 
"2022-02-28T06:00:00.000Z" 

//March 
moment(["2022","2","31"]).toISOString() 
"Invalid date" 

moment(["2022","3","30"]).toISOString() 
"2022-04-30T05:00:00.000Z" 
moment(["2022","4","31"]).toISOString() 
"2022-05-31T05:00:00.000Z" 
moment(["2022","5","30"]).toISOString() 
"2022-06-30T05:00:00.000Z" 
moment(["2022","6","31"]).toISOString() 
"2022-07-31T05:00:00.000Z" 

//August 
moment(["2022","7","31"]).toISOString() 
"Invalid date" 

moment(["2022","8","30"]).toISOString() 
"2022-09-30T05:00:00.000Z" 
moment(["2022","9","31"]).toISOString() 
"2022-10-31T05:00:00.000Z" 
moment(["2022","10","30"]).toISOString() 
"2022-11-30T06:00:00.000Z" 
moment(["2022","11","31"]).toISOString() 
"2022-12-31T06:00:00.000Z" 

然而,當我指定month參數的整數,這些日期的工作:

//March 
moment(["2022",2,"31"]).toISOString() 
"2022-03-31T05:00:00.000Z" 

//August 
moment(["2022",7,"31"]).toISOString() 
"2022-08-31T05:00:00.000Z" 

我不知道爲什麼,當我經過一個月的參數爲發生這種情況字符串與整數?

+2

您正在使用哪個版本的moment.js? – cochsen

+0

有點舊,我在意識到... https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.7.0/moment.min.js –

回答

0

原來,升級到最新版本的moment.js修復了它。

老斷裂的例子(v2.7.0): https://jsfiddle.net/1Lwauz1t/1/

最新版本的例子(v2.18.1): https://jsfiddle.net/dsadkpsa/

下面是上面的鏈接被執行的代碼的jsfiddle:

console.log(moment(["2022","2","31"]).toISOString()); 
console.log(moment(["2022",2,"31"]).toISOString()); 
console.log(moment(["2022","7","31"]).toISOString()); 
console.log(moment(["2022",7,"31"]).toISOString()); 

感謝@cochsen在正確的方向上微調。

相關問題