Java.年月日正则表达式

表达式:
yyyy-MM:
  ^([1-9]{1}[0-9]{3}[\\-]{1}){1}((1[0-2]{1}){1}|(0[1-9]{1})|([1-9]{1})){1}$
yyyy-MM-dd:
  ^((((19|20)\\d{2})(-)(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((19|20)\\d{2})(-)(0?[469]|11)-(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2})(-)(0?2)-(0?[1-9]|1\\d|2[0-8]))|(((19|20)([13579][26]|[2468][048]|0[48])|(2000))(-)(0?2)-(0?[1-9]|[12]\\d)))$
 
验证实现:
/**
    *
    * @return
    */
    private  static boolean checkYyyyMM(String strDate) {
       //验证yyyy-MM
       String regex = "^([1-9]{1}[0-9]{3}[\\-]{1}){1}((1[0-2]{1}){1}|(0[1-9]{1})|([1-9]{1})){1}$";       
       Pattern pattern = Pattern.compile(regex);
       Matcher matcher = pattern.matcher(strDate);
       boolean blnFlag= matcher.matches();
       System.out.println("Is valid year and month number: " + blnFlag);        
       return blnFlag;
   }
    
    
    private static boolean checkYyyyMMdd(String strDate) {
    
        // 编译正则表达式
        Pattern pattern = Pattern.compile("^((((19|20)\\d{2})(-)(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((19|20)\\d{2})(-)(0?[469]|11)-(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2})(-)(0?2)-(0?[1-9]|1\\d|2[0-8]))|(((19|20)([13579][26]|[2468][048]|0[48])|(2000))(-)(0?2)-(0?[1-9]|[12]\\d)))$");
        Matcher matcher = pattern.matcher(strDate);
        // 判断是否匹配
        if (matcher.matches()) {
            System.out.println("日期格式正确");
            return true;
        } else {
            System.out.println("日期格式错误");
            return false;
        }
    }

 测试示例

public static void main(String[] args) {
        // TODO Auto-generated method stub
        checkYyyyMM("2024-05");
        checkYyyyMM("2024-5");
        checkYyyyMM("2024-12");
        checkYyyyMM("2024-13");
        

        checkYyyyMMdd("2024-12-23");
        checkYyyyMMdd("2024-12-21");
        checkYyyyMMdd("2024-05-21");
        checkYyyyMMdd("2024-05-04");
        checkYyyyMMdd("2024-1-4");
        checkYyyyMMdd("2024-1-04");
checkYyyyMMdd("2024-2-29");
checkYyyyMMdd("2024-2-30");
}

测试结果

Is valid year and month number: true
Is valid year and month number: true
Is valid year and month number: true
Is valid year and month number: false
日期格式正确
日期格式正确
日期格式正确
日期格式正确
日期格式正确
日期格式正确
日期格式正确
日期格式错误

 

posted @ 2024-05-23 18:18  李文学  阅读(125)  评论(0编辑  收藏  举报