放在一起:
REGEX 不验证值(例如“ 2010-19-19”)
SimpleDateFormat 不检查格式(接受“ 2010-1-2”,“ 1-0002-003”)
必须同时验证格式和值:
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
try {
df.parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
ThreadLocal可用于避免为每个调用创建新的SimpleDateFormat。
由于SimpleDateFormat不是线程安全的,因此在多线程上下文中是必需的:
private static final ThreadLocal format = new ThreadLocal() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setLenient(false);
System.out.println("created");
return df;
}
};
public static boolean isValid(String text) {
if (text == null || !text.matches("\\d{4}-[01]\\d-[0-3]\\d"))
return false;
try {
format.get().parse(text);
return true;
} catch (ParseException ex) {
return false;
}
}
(可以对Matcher进行相同的操作,这也不是线程安全的)