views:

26

answers:

1

Alright so in Java I want to ask the user for a time in 24-hour format. I have managed to leverage DateFormat and SimpleDateFormat to tell it what format the time is being entered in and then to interpret that accordingly, throwing an exception if it does not follow that format. Here is what I have:

DateFormat fmt = new SimpleDateFormat("HH:mm");
Scanner keyboard = new Scanner(System.in);

try {
    String input = keyboard.nextLine();
    Date theDate = fmt.parse(input);
    System.out.println(theDate.toString());
} catch (ParseException e) {
    System.out.println("Incorrect format!");
    e.printStackTrace();
}

If I type in a word, it indeed throws an exception. However, if I type in something like 234234:2342342 it actually goes and does the math to figure out how many days those hours and minutes equate to, then outputs the actual date. For example, given input:

input: 23423423:232323
output: Fri Jul 29 07:03:00 PDT 4642

I am wondering if there is a way to treat this as an exception. So I want to only accept what the formatters specify (H 0-23 and m 0-59), and if it does not fall within these boundaries, throw an exception or have some way of knowing. What I would like to know is if there is a way to do this within the formatter classes I am using, or if it should be done using the Scanner class (how?), or if I have to write the parsing and validation code myself. Am I approaching this completely wrong? I am currently just trying out the possibilities, so if there is a better way please let me know.

Thanks!

+5  A: 

I figured it out, using DateFormat's setLenient method.

fmt.setLenient(false);

Now typing in anything that doesn't fit the format (hour = 0 to 23 and minute = 0 to 59) it throws an exception :)

Jorge Israel Peña
I think you're about to get a Self-Learner badge :)
Dolph