[英]SimpleDateFormat and parsing: parse doesn't fail with wrong input string date
我正在使用
java.util.Date date;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(inputString);
} catch (ParseException e) {
e.printStackTrace();
}
其中inputString
是dd/MM/yyyy
格式的字符串。
例如,如果inputString
是40/02/2013,我将获得一个错误,而parse方法将返回Date 2013年3月12日(2013年3月12日)。 我错了什么?
设置宽松位 :
public void setLenient(boolean lenient)
指定日期/时间解析是否宽松。 通过宽松的解析,解析器可以使用启发式来解释与该对象的格式不完全匹配的输入。 通过严格的解析,输入必须与此对象的格式匹配。
以下代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class Tester {
public static void main(String[] argv) {
java.util.Date date;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
// Lenient
try {
date = sdf.parse("40/02/2013");
System.out.println("Lenient date is : "+date);
} catch (ParseException e) {
e.printStackTrace();
}
// Rigorous
sdf.setLenient(false);
try {
date = sdf.parse("40/02/2013");
System.out.println("Rigorous date (won't be printed!): "+date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
得到:
Lenient date is : Tue Mar 12 00:00:00 IST 2013
java.text.ParseException: Unparseable date: "40/02/2013"
at java.text.DateFormat.parse(DateFormat.java:357)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.