[英]SimpleDateFormat and parsing: parse doesn't fail with wrong input string date
I'm using 我正在使用
java.util.Date date;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse(inputString);
} catch (ParseException e) {
e.printStackTrace();
}
where inputString
is a string in the dd/MM/yyyy
format. 其中
inputString
是dd/MM/yyyy
格式的字符串。
If the inputString
is, for example, 40/02/2013, I would to obtain an error, instead the parse method returns the Date 12 March 2013 (12/03/2013). 例如,如果
inputString
是40/02/2013,我将获得一个错误,而parse方法将返回Date 2013年3月12日(2013年3月12日)。 What I'm wronging? 我错了什么?
Set the Leniency bit : 设置宽松位 :
public void setLenient(boolean lenient)
Specify whether or not date/time parsing is to be lenient.
指定日期/时间解析是否宽松。 With lenient parsing, the parser may use heuristics to interpret inputs that do not precisely match this object's format.
通过宽松的解析,解析器可以使用启发式来解释与该对象的格式不完全匹配的输入。 With strict parsing, inputs must match this object's format.
通过严格的解析,输入必须与此对象的格式匹配。
The following code: 以下代码:
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();
}
}
}
Gives: 得到:
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.