Aram Kirakosyan
Aram Kirakosyan

Reputation: 11

SimpleDateFormat Exception

Hi I am using SimpleDateFormat for parsing and comparing two dates from strings. here is my code

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;
    } 

And here is a main method

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");
    }

}

This works normally when I am passing valid arguments, but ! want to have an exception when passing for example "28:40:04", now I have an exceptions only when passing as an argument string containing letters.

Upvotes: 0

Views: 93

Answers (1)

reto
reto

Reputation: 10473

You need to set lenient to false (the default behavior is lenient):

sdf.setLenient(false);

See What is the use of "lenient "? and the javadoc:

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.

Upvotes: 3

Related Questions