好啦,各位大侠,多谢你们的关注!我在网上已经找到判断方法了,不用正则表达式,到目前为止,经测试没有发现bug,现贴出来供大家参考。 public static boolean checkValidDate( String pDateObj ) { boolean ret = true; if(pDateObj==null||pDateObj.length()!=8){ ret = false; } try{ int year = new Integer(pDateObj.substring( 0, 4 )).intValue(); int month = new Integer(pDateObj.substring( 4, 6 )).intValue(); int day = new Integer(pDateObj.substring( 6 )).intValue(); Calendar cal = Calendar.getInstance(); cal.setLenient( false ); //允许严格检查日期格式 cal.set(year, month-1, day); cal.getTime();//该方法调用就会抛出异常 }catch( Exception e ) { ret = false; } return ret; }
或是第三方包也有
Date date = null;
//SimpleDateFormate.parse();}catch(Execption e){
//something
}if(date==null){
//something
}
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String d = "19801132";
try{
Date date = df.parse(d);
return true;
}catch(ParseException pe){
return false;
}
void main()
{int a,b,c;
}
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String d = "19801132";
try{
Date date = df.parse(d);
return true;
}catch(ParseException pe){
return false;
}
class A{
public static void main(String args[]) { String str="19801132";//"20051121"则为true String regEx="(19|20)\\d\\d(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])";
Pattern p=Pattern.compile(regEx);
Matcher m=p.matcher(str);
boolean result=m.find();
System.out.println(result);
}
}
String regEx="(19|20)\\d\\d((0[1|3-9]|1[012])(0[1-9]|[12][0-9]|3[01]))|2(0[1-9]|1[0-9]|2[0-8])";
假设2月只有28天。正确的日期,输出true
import java.text.*;
用正则式我认为是不可取的
2003-02-31要完善一下
String regEx="(19|20)\\d\\d((0[1|3-9]|1[012])(0[1-9]|[12][0-9]|3[01]))|2(0[1-9]|1[0-9]|2[0-8])";
假设2月只有28天。
正确的日期,输出true
--------------------------
还得判断平年,闰年
需要再加一函数,判断日期的合法性
正则式判断不了,只能判断形式上正确与否,比如20000231,形式上是对的,却是非法的
--------------------------------------------------------------------------------
暮色兄是对的,只能判断格式
搂主要判断日期的合法性
需要将年月日分别取出进行判断
ps: 可以在输入的时候进行判断,然后放在Calendar类型的对象中
如果正则式判断不了日期合法性,Java中任何东西都不能判断日期合法性;
如果Java中有其他东西能判断日期合法性,则正则式一定能够判断日期合法性。To glnpu_dd(涉江采芙蓉) :“还得判断平年,闰年”。这是对的。但这不需要再加一函数。
打个比如,如果我写 System.out.print("hi"),
遇到中国人需要加一个System.out.print("你好"),不需要更多特别的技术。判断日期合法性可能还需要考虑1880年等等,这是我们必须完善的,不是正则式本身的问题。To believefym:“正则式判断不了,只能判断形式上正确与否,比如20000231,形式上是对的,却是非法的”,
错误的说法。如果不能判断出20000231为非法,只能说明你的正则式有问题。如同我写的正则式遇到闰年出问题一样,这不是正则式本身的问题,而是我写的正则式不满足需求。“用正则式我认为是不可取的”,如果DateFormat能够满足你的需求,当然要不要正则式就无所谓了。
public static boolean checkValidDate( String pDateObj ) {
boolean ret = true;
if(pDateObj==null||pDateObj.length()!=8){
ret = false;
}
try{
int year = new Integer(pDateObj.substring( 0, 4 )).intValue();
int month = new Integer(pDateObj.substring( 4, 6 )).intValue();
int day = new Integer(pDateObj.substring( 6 )).intValue();
Calendar cal = Calendar.getInstance();
cal.setLenient( false ); //允许严格检查日期格式
cal.set(year, month-1, day);
cal.getTime();//该方法调用就会抛出异常
}catch( Exception e ) {
ret = false;
}
return ret;
}
cal.setLenient( false ); //允许严格检查日期格式
这句话很重要。