读书人

java 判定日期是不是符合yyyy-mm-dd

发布时间: 2012-10-11 10:16:10 作者: rapoo

java 判定日期是否符合yyyy-mm-dd
//判定日期格式的正确性
public boolean isValidDate(String sDate) {
String datePattern1 = "\\d{4}-\\d{2}-\\d{2}";
String datePattern2 = "^((\\d{2}(([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{2}(([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;
}

//格式化日期,Date转化string
public static String formatDate(Date date){
SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd");
return dateformat.format(date);
}

//判定日期的是否超前
public static boolean isDateAfter(String sDate){
try{
if(DateFormat.getDateInstance().parse(sDate).compareTo(DateFormat.getDateInstance().parse(formatDate(new Date())))==1)
return false;
else return true;
}catch(ParseException e){
return false;
}
}
//将string转化为date
public static Date StringToDate(String dateStr){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date bdate = null;
try {
bdate = formatter.parse(dateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bdate;
}

读书人网 >编程

热点推荐