Checking the Time format..

Hello Friends,

I have a string s ="10:12 PM" (something like this). I want to check that this is the correct format of Time or not. For that I have used the Pattern class of Java and have a code like

Pattern p = Pattern.compile("(\\d)(\\d)(:)(\\d)(\\d)(\\s)(A|P)(M)");

Matcher m = p.matcher("10:20 AM");

boolean b = m.matches();

System.out.println(b);

This code is running perfect, but I want to check for one more thing. I want to check that hours fall in range 0-11 and minutes fall in range 0-59, but pattern class dont have any range check for digit(we can do that on char). Please suggest me a solution.

Thanks,

-Vaibhav-

[684 byte] By [bronze-starDukes] at [2007-11-26 12:15:43]
# 1

How about using SimpleDateFormat instead and catching the exception in case of mal formed time string?

SimpleDateFormat f = new SimpleDateFormat("K:m a");

try

{

f.parse("10:24 AM");

}

catch (ParseException e)

{

e.printStackTrace();

}

Message was edited by:

Peetzore

bronzestar at 2007-7-7 14:19:51 > top of Java-index,Archived Forums,Socket Programming...
# 2
Hey Peetzore,This is a nice way, but the problem remains as it is. if I am giving :f.parse("10:240 AM")); in place of f.parse("10:24 AM")); its not throwing the error, its internal get converted into the right stuff. But I want a error msg.Thanks-Vaibhav-
bronzestar at 2007-7-7 14:19:51 > top of Java-index,Archived Forums,Socket Programming...
# 3
add this snippet after you create the formatter but before you try to parse anything:f.setLenient(false);
platinumsta at 2007-7-7 14:19:51 > top of Java-index,Archived Forums,Socket Programming...