Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple time parsing of a String

Tags:

java

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

    }
like image 320
ashwinsakthi Avatar asked Dec 26 '22 19:12

ashwinsakthi


1 Answers

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.

like image 101
Vikdor Avatar answered Jan 13 '23 01:01

Vikdor