parsing a time field with SimpleDateFormat

Our users can not key in a military time, they must key in a time with the ampm designation. We allow a for am, p for pm, m for midnight and n for noon. (Don't ask-I guess they don't understand 12:00pm or 12:00am so they specify 12:00m for midnight and 12:00n for noon.)

I want to use the parse function, with lenient set to false to validate that they keyed a valid date. This works fine when they key a or p behind the date. If they key m or n, it gives an error. I tried using DateFormatSymbols to allow a,p,m or n for the AmPmStrings. This works fine if lenient is set to true. With lenient set to false, it still gives me an invalid date. I guess it is not recognizing my DateFormatSymbol.

Not sure if I am going about this the wrong way or if there is an easier way to validate the time. I just thought the parse would be a cleaner way then to substring out the hours and minutes, then validate that they are valid numbers.

Below is the code I was using. Can anyone explain why this won't work?

DateFormatSymbols symbols = new DateFormatSymbols();

String[] ampm = new String[4];

ampm[0] = new String("A");

ampm[1] = new String("P");

ampm[2] = new String("M");

ampm[3] = new String("N");

symbols.setAmPmStrings(ampm);

SimpleDateFormat df = new SimpleDateFormat("hhmma", symbols);

df.setLenient(false);

try

{

parsedTime = df.parse(time.toUpperCase());

return true;

}

catch (ParseException e)

{

errorMessages.add("Invalid Date.");

return false;

}

[1593 byte] By [latidwell] at [2007-9-27 22:49:43]
# 1

Well, this isn't gonna help you, but-

I can't say unequivocally(sp) that this is the case, but after a bit of poking about, it appears that the DateFormatSymbols.setAmPmStrings method ignores everything but the first two entries in the string. That is, if you use

ampm[0] = new String("M");

ampm[1] = new String("N");

ampm[2] = new String("A");

ampm[3] = new String("P");

You will be able to parse M's and N's, but not A's and P's.

Not sure if that helps you, but there you go.

Lee

tsith at 2007-7-7 13:56:28 > top of Java-index,Archived Forums,New To Java Technology Archive...
# 2

One thing you could do would be to set the n to p and m to a once the date is entered. Something likeString theTime;

//theTime is given a value that is entered from the user

String tempTime = theTime.replaceAll("n","p").replaceAll("m","a");

Brian-74-454 at 2007-7-7 13:56:28 > top of Java-index,Archived Forums,New To Java Technology Archive...
# 3
Thank you to both of you for your help. I did not know the setAmPmStrings only looked at the first two entries.I did do a work around by changing the entries after they were entered. Being new at Java, I had not used the replaceAll yet. That was a much quicker way. THANKS!
latidwell at 2007-7-7 13:56:28 > top of Java-index,Archived Forums,New To Java Technology Archive...