您好,我正在使用SimpleDateFormat解析和比较字符串中的两个日期。以下是我的代码
private static int compareDates(String lineFromFile, String givenDate) throws ParseException, IllegalArgumentException
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date dateFromfile = sdf.parse(tmp);
Date givenDateTime = sdf.parse(givenDate);
if (dateFromfile.equals(givenDateTime))
{
return 0;
}
if (dateFromfile.before(givenDateTime))
{
return 1;
}
return -1;
} 下面是一个主要的方法
public static void main(String[] args) {
try
{
int result = compareDates("00:45:44", "09:35:56");
System.out.println(line);
}
catch (ParseException e)
{
e.printStackTrace();
System.out.println("ERROR");
}
}当我传递有效的参数时,这是正常的,但是!我希望在传递例如"28:40:04“时有异常,现在我只有在作为包含字母的参数字符串传递时才有异常。
发布于 2013-10-29 20:29:02
您需要将lenient设置为false (默认行为为lenient):
sdf.setLenient(false);请参阅What is the use of "lenient "?和javadoc
指定日期/时间解析是否宽松。通过宽松的解析,解析器可以使用启发式方法来解释与此对象的格式不完全匹配的输入。在严格解析的情况下,输入必须与此对象的格式匹配。
https://stackoverflow.com/questions/19658137
复制相似问题