java中驗證日期格式
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateTimeCheck {
/**
* 驗證日期時間格式
*
* @param args
*/
public static void main(String[] args) {
String checkValue = "2008-09-11 14:17:11";
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
Date d = null;
if (checkValue != null && !checkValue.equals("")) {
if (checkValue.split("/").length > 1) {
dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}
if (checkValue.split("-").length > 1) {
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
} else {
return;
}
try {
d = dateFormat.parse(checkValue);
System.out.println(d);
} catch (Exception e) {
System.out.println("格式錯誤");
return;
}
Pattern p = Pattern.compile(eL);
Matcher m = p.matcher(checkValue);
boolean b = m.matches();
if (b) {
System.out.println("格式正確");
} else {
System.out.println("格式錯誤");
}
}
}