我正在验证无效日期,例如 36/12/2013 (DD/MM/YYYY)、2/15/2013 (DD/MM/YYYY) 或以下特定情况:
29/02/2009 (DD/MM/YYYY) 无效,因为 2009 年不是闰年
代码是:
var momentAcceptedDateInputs = ['D/M/YY', 'DD/M/YY','D/MM/YY','DD/MM/YY'
, 'D/M/YYYY', 'DD/M/YYYY', 'D/MM/YYYY', 'DD/MM/YYYY',
'D MMM YY', 'DD MMM YY', 'D MMM YYYY', 'DD MMM YYYY'];
var parsedDate = moment(val, momentAcceptedDateInputs);
return parsedDate.isValid();
输入值:
29/02/2009
预期对象的返回值:
- parsedDate.isValid(): false
- parsedDate:时刻
- _a: 数组[7]
- _d:2009 年 2 月 29 日星期日 00:00:00 GMT+1300(新西兰夏令时间)
- _f: "D/M/YYYY"
- _i:“2009 年 2 月 29 日”
- _isUTC: 假
- _isValid:假
实际对象的返回值:
- parsedDate.isValid(): 真
- parsedDate:时刻
- _a: 数组[7]
- _d:1920 年 2 月 29 日星期日 00:00:00 GMT+1300(新西兰夏令时间)
- _f: "D/M/YY"
- _i:“2009 年 2 月 29 日”
- _isUTC: 假
- _isValid:真
知道如何解决这个问题吗?
我正在使用moment.js的自定义版本:2.4.0
我自定义的唯一规则是这个,所以我怀疑它会导致上面报告的错误:
datePartArray[YEAR] = toInt(input) +
(toInt(input) > (moment(moment()).format("YY")) ? 1900 : 2000);
最佳答案
Moment 的解析器默认是非常宽容的。
例如:
moment("29/02/2009",'D/M/YY').isValid() // true, because it uses year "20"
你可以通过传递一个 bool 值来改变它
moment("29/02/2009",'D/M/YY', true).isValid() // false, due to the year digits
关于javascript - MomentJS 问题处理 2 月 29 日不是闰年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319249/