当我将年,月,日作为字符串传递给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"
我想知道为什么当我将Month参数作为字符串与整数传递时会发生这种情况?
答案 0 :(得分: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在正确的方向上轻推。