日期:2014-05-16 浏览次数:20392 次
Step 2,给出解决问题的代码实现: ?var dateSourcePattern = 'yyyy-MM-dd HH:mm:ss' ;
var dateFormatPattern = dateSourcePattern
.replace('yyyy','[0-9]{4}')
.replace('MM','[0-9]{1,2}')
.replace('dd','[0-9]{1,2}')
.replace('HH','[0-9]{1,2}')
.replace('mm','[0-9]{1,2}')
.replace('ss','[0-9]{1,2}');
?这样转化为了正则后,就可以与以前的日期进行匹配了。
<html> <head></head> <body> </body> </html> <script type="text/javascript"> /* dateISO('2010-12-10 17:25:10', 'yyyy-MM-dd HH:mm:ss'); //验证通过 dateISO('2010-12-10 17:25:10', 'yyyy-MM-dd HH:mm'); //验证不通过 dateISO('2010-12-10', 'yyyy-MM-dd'); //验证通过 dateISO('2010-12-10 17:25', 'yyyy-MM-dd HH:mm'); //验证通过 dateISO('17:25:10', 'HH:mm:ss'); //验证通过 */ var DateFormatter = { Patterns:{ YEAR : /y/g, MONTH : /M/g, DAY : /d/g, HOUR : /H/g, MINUTE : /m/g, SECOND : /s/g, MILSECOND : /f/g }, FormatPatterns:function(format){ return eval("/"+ format .replace(this.Patterns.YEAR,'[0-9]') .replace(this.Patterns.MONTH,'[0-9]') .replace(this.Patterns.DAY,'[0-9]') .replace(this.Patterns.HOUR,'[0-9]') .replace(this.Patterns.MINUTE,'[0-9]') .replace(this.Patterns.SECOND,'[0-9]') .replace(this.Patterns.MILSECOND,'[0-9]')+ "/g"); }, DateISO:function(value,format){ var formatReg = ""; if(value == "" || format=="") return false; formatReg = this.FormatPatterns(format); alert(formatReg); return formatReg.test(value); } } var ret = DateFormatter.DateISO('2010-1d-10 17:25:10', 'yyyy-MM-dd HH:mm:ss'); alert(ret); //false var ret1 = DateFormatter.DateISO('2010-10-10 17:25:10', 'yyyy-MM-dd HH:mm:ss'); alert(ret1); //true </script>?