Simple string time analysis

In the code below, I need to get a parsing exception. But the program somehow converts it to a valid date.

But if I give dthours as "07: 0567", it gives a parsing error. So how to save the exact format.

Can someone tell me what to do to throw an error if the date string deviates from this format ("HH: MM: SS") even with one character.

public static void main(String[] args) { String dthours="07:4856:35563333"; SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS"); try { Date d = df.parse(dthours); System.out.println("d "+d); } catch (ParseException e) { System.out.println("parseError"); } 
+4
source share
1 answer

Set the df.setLenient () parameter to false so that SimpleDateFormat selects a parsing exception in such cases.

 public static void main(String[] args) { String dthours = "07:4856:35563333"; SimpleDateFormat df = new SimpleDateFormat("HH:MM:SS"); df.setLenient(false); try { Date d = df.parse(dthours); System.out.println("d = " + d); } catch (ParseException e) { System.out.println("parseError"); } } 

The above snippet will print "parseError" for this input.

+10
source

All Articles