java 判断日期格式是否正确,日期是否规范

来源:互联网 发布:apache location 配置 编辑:程序博客网 时间:2024/04/27 19:14
给你一个我自己定义的import java.util.Date;import java.util.regex.Matcher;import java.util.regex.Pattern;public static boolean isValidDate(String sDate) {     String datePattern1 = "\\d-\\d-\\d";     String datePattern2 = "^((\\d(([02468][048])|([13579][26]))"             + "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"             + "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"             + "((0?[1-9])|([1-2][0-9])))))|(\\d(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?("             + "(((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?"             + "((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))";     if ((sDate != null)) {         Pattern pattern = Pattern.compile(datePattern1);         Matcher match = pattern.matcher(sDate);         if (match.matches()) {             pattern = Pattern.compile(datePattern2);             match = pattern.matcher(sDate);             return match.matches();         }         else {             return false;         }     }     return false; }格式必须为“YYYY-MM-DD”  //你也可以自己定义2004-2-30 是无效的2003-2-29 是无效的
2------------------------------------------
 public   boolean   checkValidDate(   String   pDateObj   )   {             if(pDateObj==null){                 return false;            }             try{          String str[]=pDateObj.split("-");        if(str.length!=3){        return false;       }            int year=  Integer.parseInt(str[0]);               int month=  Integer.parseInt(str[1]);               int day=  Integer.parseInt(str[2]);               Calendar   cal   =   Calendar.getInstance();               cal.setLenient(false);   //允许严格检查日期格式               cal.set(year,   month-1,   day);               cal.getTime();//该方法调用就会抛出异常           }catch(   Exception   e   )   {          return false;             }           return  true;     }
                                             
0 0
原创粉丝点击