Java验证字符串是否符合日期格式
很多时候我们需要验证字符串是否是正确的日期格式,在这里做一个总结
/**
* 验证日期格式是否满足要求
*
* @param str 需要验证的日期格式
* @param formatString 验证的标准格式,如:(yyyy/MM/dd HH:mm:ss)
* @return 返回验证结果
*/
public static boolean isValidDate(String str, String formatString) {
// 指定日期格式,注意yyyy/MM/dd区分大小写;
SimpleDateFormat format = new SimpleDateFormat(formatString);
try {
// 设置lenient为false.
// 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
format.setLenient(false);
format.parse(str);
} catch (ParseException e) {
// e.printStackTrace();
// 如果throw java.text.ParseException或者NullPointerException,就说明格式不对
return false;
}
return true;
}
本文介绍了一种使用Java进行日期格式验证的方法,通过SimpleDateFormat类配合setLenient(false)方法,可以精确验证字符串是否符合特定的日期格式,如yyyy/MM/dd HH:mm:ss。
1606

被折叠的 条评论
为什么被折叠?



