var a = '2011-12-21';
var d = '12/21/2011';
function test(s){
var r1 = /^(\d{2})\/(\d{2})\/(\d{4})$/;
if(r1.test(s)){
s = RegExp.$3+'-'+RegExp.$1+'-'+RegExp.$2;
return Boolean(+new Date(s));
}else{
var r1 = /^(\d{4})([-/]?)(\d{2})\2(\d{2})$/;
if(r1.test(s)){
s = RegExp.$1+'-'+RegExp.$3+'-'+RegExp.$4;
return Boolean(+new Date(s));
}else{
return false;
}
}
}
console.log(test(a));
console.log(test(b));
console.log(test(c));
console.log(test(d));
这个并非标准正则,按照语义,应该是支持三种。测试一下就知道了。
这个要是用正则的话反而麻烦了,还是判断截取字符串再判断吧
仅供参考,希望对你有所帮助。
static public boolean testDateFormat(String dateFormat){
Pattern p = Pattern.compile("\\d{4}[-/]?\\d{2}[-/]?\\d{2}||\\d{2}/\\d{2}/\\d{4}");
Matcher m = p.matcher(dateFormat);
return m.matches();
}