In the below code i need to get a parse exception.but the program somehow converts it to a valid date.
But if i give dthours as "07:0567" it is giving parse error.So how to keep the exact format shown.
Can anyone tell me what to do to throw an error if the date string deviates from the given format ("HH:MM:SS") even by a single 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");
}
Set the df.setLenient() to false so that the SimpleDateFormat will throw parse 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 would print "parseError" for that input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With