JavaScript中检测无效日期实例的方法 技术背景 在JavaScript里,创建日期对象时可能会得到无效的日期实例,像 new Date('foo')
。所以,准确检测日期对象是否有效是很重要的。
实现步骤 1. 基本方法 借助 Object.prototype.toString.call
与 isNaN
来检测:
1 2 3 4 5 6 7 8 9 10 if (Object .prototype .toString .call (d) === "[object Date]" ) { if (isNaN (d)) { } else { } } else { }
2. 简化方法 若不考虑来自其他JS上下文的日期对象,可采用如下更简单的形式:
1 2 3 function isValidDate (d ) { return d instanceof Date && !isNaN (d); }
3. 利用 Date.parse
方法 使用 Date.parse
解析日期字符串并检查结果:
1 2 3 4 5 var timestamp = Date .parse ('foo' );if (isNaN (timestamp) == false ) { var d = new Date (timestamp); }
4. 自定义方法 给 Date
原型添加 isValid
方法:
1 2 3 4 5 6 7 8 9 10 Date .prototype .isValid = function ( ) { return this .getTime () === this .getTime (); };var d = new Date ("lol" );console .log (d.isValid ()); d = new Date ("2012/09/11" );console .log (d.isValid ());
5. 最简方法 使用 isNaN
或 isFinite
直接检查:
1 2 3 4 5 6 7 isNaN (date); !isNaN (date);isFinite (date);
在TypeScript中:
6. 其他方法 利用 toString
方法 1 2 3 function isValidDate (dateObject ) { return new Date (dateObject).toString () !== 'Invalid Date' ; }
使用 moment.js
1 2 var m = moment ('2015-11-32' , 'YYYY-MM-DD' ); m.isValid ();
使用 jQuery UI DatePicker 1 2 3 4 5 6 7 8 9 var stringval = '01/03/2012' ;var testdate;try { testdate = $.datepicker.parseDate ('mm/dd/yy' , stringval); } catch (e) { alert (stringval + ' is not valid. Format must be MM/DD/YYYY ' + 'and the date value must be valid for the calendar.' ); }
自定义日期验证函数 1 2 3 4 function isDate (txt ) { var matches = txt.match (/^\d?\d\/(\d?\d)\/\d{4}$/ ); return !!matches && !!Date .parse (txt) && new Date (txt).getDate () == matches[1 ]; }
核心代码 下面是一些核心代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 function isValidDate (d ) { return d instanceof Date && !isNaN (d); }Date .prototype .isValid = function ( ) { return this .getTime () === this .getTime (); };function isDate (txt ) { var matches = txt.match (/^\d?\d\/(\d?\d)\/\d{4}$/ ); return !!matches && !!Date .parse (txt) && new Date (txt).getDate () == matches[1 ]; }
最佳实践 若项目里已经使用了 moment.js
或 date-fns
这样的日期处理库,建议使用它们提供的日期验证方法,因为这些方法功能更强大,兼容性也更好。 若要验证日期字符串,可结合正则表达式与 Date.parse
方法,以此确保日期格式与有效性。 尽量避免直接使用 new Date()
来解析日期字符串,因为它在不同浏览器和环境下可能有不同的解析结果。 常见问题 跨框架问题 :使用 instanceof
检查日期对象时,可能会出现跨框架问题。可使用 Object.prototype.toString.call
替代。日期格式问题 :JavaScript 的 Date
对象能解析多种日期格式,不过不同浏览器的解析结果可能不同。建议使用统一的日期格式,并结合正则表达式进行验证。闰年问题 :在验证日期时,要考虑闰年的情况,比如 2 月 29 日。可通过检查年份是否为闰年,再验证日期的有效性。