0

您好我正在使用 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”时出现异常,现在我只有在作为包含字母的参数字符串传递时才会出现异常。

4

1 回答 1

3

您需要将 lenient 设置为false(默认行为是 lenient):

sdf.setLenient(false);

请参阅“宽容”有什么用?javadoc

指定日期/时间解析是否宽松。通过宽松的解析,解析器可以使用启发式方法来解释不精确匹配该对象格式的输入。使用严格的解析,输入必须匹配这个对象的格式。

于 2013-10-29T12:29:01.703 回答