java 编程从屏幕输入8-10位字符串,判断是否为日期

,格式如下几种 2013/01/01 20130101 ”2013/1/1"

public static void main(String[] args)   
    {   
        String checkValue = "2000/03/31";
        checkValue = checkValue.replaceAll("/", "")+"000000";
String year = checkValue.substring(0, 4); // 获取年份
String month = checkValue.substring(4, 6); // 获取月份
        Boolean isLeap = leapYear(Integer.parseInt(year)); // 判断闰年
        System.out.println(isLeap);
        StringBuffer eL= new StringBuffer();
        String longMonth = "01030507081012"; // 31天的月份
        String fix = "([2][0-3]|[0-1][0-9]|[1-9])[0-5][0-9]([0-5][0-9]|[6][0])";
        
        
        if(isLeap && month.equals("02")){  // 针对2月份的情况 【闰年】
         eL.append("\\d{4}([1][0-2]|[0][0-9])([2][0-1]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
        }else if(!isLeap && month.equals("02")){ // 针对2月份的情况 【非闰年】
         eL.append("\\d{4}([1][0-2]|[0][0-9])([2][0-1]|[1-2][0-8]|[0][1-9]|[1-9])"+fix);
        }else if(longMonth.contains(month)){ // 31天月份
         eL.append("\\d{4}([1][0-2]|[0][0-9])([3][0-1]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
        }else{ // 30天月份
         eL.append("\\d{4}([1][0-2]|[0][0-9])([3][0]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
        }
        Pattern p = Pattern.compile(eL.toString());    
        Matcher m = p.matcher(checkValue);    
        boolean flag = m.matches();   
        if(flag )   
        {         
            System.out.println("格式正确");   
        }   
        else  
        {   
            System.out.println("格式错误");   
        }   
  
    } 
public static boolean leapYear(int year) {
Boolean isLeap = false;
if (((year % 100 == 0) && (year % 400 == 0))
|| ((year % 100 != 0) && (year % 4 == 0)))
isLeap = true;
return isLeap;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-11-05
如2013/01/01
/^(\d{4})/(0\d{1}|1[0-2])/(0\d{1}|[12]\d{1}|3[01])$/
20130101
/^(\d{4})(0\d{1}|1[0-2])(0\d{1}|[12]\d{1}|3[01])$/
2013/1/1
/^(\d{4})/(\d{1}|1[0-2])/(\d{1}|[12]\d{1}|3[01])$/
第2个回答  2017-08-14
可以用正则表达式判断:
import java.util.Scanner;
class ThreadDemo{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();

//已考虑平闰年
String reg="(?:(?!0000)[0-9]{4}/((?:(?:0[1-9]|1[0-2])|[1-9])/([1-9]|(?:0[1-9]|1[0-9]|2[0-8]))|(?:0[13-9]|1[0-2])/(?:29|30)|(?:0[13578]|1[02])/31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)/02/29)";

System.out.println(str.matches(reg));
}
}
第3个回答  2013-11-05
要是我,就直接转换成Date类型,然后去捕获异常,捕获到异常则表示不是日期类型追问

我看书,是不允许用异常捕获的,那样难以阅读,而且速度非常慢。
异常机制只是为程序的意外情况准备的

追答

你要是不想用异常捕获,就只能用正则了,要完全判断写起来相当麻烦,因为不同的月份会影响都天数,还有闰年/平年.

你要是真想用正则,这有一篇关于日期正则的博客,写的相当全,你可以参考下.
http://www.cnblogs.com/jay-xu33/archive/2009/01/08/1371953.html