我竟然为了判断是不是日期,用了这么复杂的代码!谁给我个简单的建议啊。
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;
public class IsDate{
public static void main(String[] args) throws Exception{
boolean is_date = isDate("1000-2-29");
System.out.println(is_date);
}
public static boolean isDate(String strDate){
try {
Pattern datePattern = Pattern.compile("([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})");
Matcher dateParts = datePattern.matcher(strDate);
if (dateParts.find()){
int iYear = getIntValue(dateParts.group(1));
int iMonth = getIntValue(dateParts.group(2));
int iDay = getIntValue(dateParts.group(3));
if (checkDate(iYear, iMonth, iDay)) return true;
else
return false;
} else
return false;
} catch (PatternSyntaxException pse){ return false;
}
}
public static boolean checkDate(int iYear, int iMonth, int iDay){
int[] amonths = {1, 3, 5, 7, 8, 10, 12};
int[] bmonths = {4, 6, 9, 11};
for (int i = 0;
i < amonths.length;
i++)
if (iMonth == amonths &&
iDay < 32) return true;
for (int i = 0;
i < bmonths.length;
i++)
if (iMonth == bmonths &&
iDay < 31) return true;
if (iMonth ==2){
if (isLeapYear(iYear) &&
iDay < 30) return true;
else
if (iDay < 29) return true;
}
return false;
}
public static boolean isLeapYear(int iYear){
if (iYear % 4 == 0){
if ((iYear % 100 == 0) &&
(iYear % 400 != 0)) return false;
else
return true;
} else
return false;
}
public static int getIntValue(String strInt){
try {
return Integer.parseInt(strInt);
} catch (Exception e){ return 0;
}
}
}