SimpleDateFormat.setLenient(bool flag);是一个可自动判定日期是否合法的方法,在使用过程中很方便;
使用方法例如:输入“2015.10.33”在SimpleDateFormat.setLenient(true);的时候可以输出;而在SimpleDateFormat.setLenient(false);抛出异常。
package date;
import java.text.SimpleDateFormat;
/**
* Created by taoyongpan on 2016/10/12.
*/
public class JudgeDate {
public static void main(String[]args)
{
String str="2007-5-32";
if(isDate(str,"yyyy.MM.dd")|isDate(str,"yyyy-MM-dd"))
System.out.print(str);
else
System.out.println("This is wrong");
}
public static boolean isDate(String str_input,String rDateFormat){
if (!isNull(str_input)) {
SimpleDateFormat format = new SimpleDateFormat(rDateFormat);
format.setLenient(false);
try {
format.format(format.parse(str_input));
} catch (Exception e) {
return false;
}
return true;
}
return false;
}
public static boolean isNull(String str){
if(str==null)
return true;
else
return false;
}
}
输出结果是“This is wrong”
package date;
import java.text.SimpleDateFormat;
/**
* Created by taoyongpan on 2016/10/12.
*/
public class JudgeDate {
public static void main(String[]args)
{
String str="2007-5-32";
if(isDate(str,"yyyy.MM.dd")|isDate(str,"yyyy-MM-dd"))
System.out.print(str);
else
System.out.println("This is wrong");
}
public static boolean isDate(String str_input,String rDateFormat){
if (!isNull(str_input)) {
SimpleDateFormat format = new SimpleDateFormat(rDateFormat);
format.setLenient(true);
try {
format.format(format.parse(str_input));
} catch (Exception e) {
return false;
}
return true;
}
return false;
}
public static boolean isNull(String str){
if(str==null)
return true;
else
return false;
}
}
输出结果是“2007-5-32”;
综上 ,我们使用的过程中,要设置为false;