Forums Register Login

time validation

+Pie Number of slices to send: Send
I found and reviewed a similar post from 2004 and my code seems to be similar with that found in that post. However, I am not receiving the results that I expected. When I test this code against an invalid time of 02:65:10 it validates it as being 03:05:10 where it increments the hour by 1 and decreases the minutes by 60. Following is my code. Any help is appreciated.

SimpleDateFormat sdf;

if (Pattern.matches(("([0-9]{2}[\\:][0-9]{2}[\\:][0-9]{2})"), fieldValue)) {
sdf = new SimpleDateFormat("HH:mm:ss");
} else if (Pattern.matches(("([0-9]{2}[\\.][0-9]{2}[\\.][0-9]{2})"), fieldValue)) {
sdf = new SimpleDateFormat("HH.mm.ss");
} else if (Pattern.matches(("([0-9]{2}[\\:][0-9]{2})"), fieldValue)) {
sdf = new SimpleDateFormat("HH:mm");
} else if (Pattern.matches(("([0-9]{2}[\\.][0-9]{2})"), fieldValue)) {
sdf = new SimpleDateFormat("HH.mm");
} else if (Pattern.matches(("([0-9]{6})"), fieldValue)) {
sdf = new SimpleDateFormat("HHmmss");
} else if (Pattern.matches(("([0-9]{4})"), fieldValue)) {
sdf = new SimpleDateFormat("HHmm");
} else {
return 3011;
}
try {
Date testTime = sdf.parse(fieldValue);
System.out.println(fieldValue + " " + testTime);
return 0;
} catch (ParseException e) {
e.printStackTrace();
return 3011;
}

Rod
+Pie Number of slices to send: Send
Set the leniency of your DateFormat to false.
+Pie Number of slices to send: Send
I'm not an expert, but I think it is working as intended. If you look at that, it is saying 2 o'clock and 65 miniutes, which would be 3:05. Maybe you could alter your conditions so the minutes can only be between 0-59? Hours between 0-23, or 1-12, depending what you are using.

Or you can listen to Rob, because he types faster than I do. And clearly knows what he is talking about .
+Pie Number of slices to send: Send
Thank you for all who replied. My code now works using setLenient as Rob mentioned.

Rod
A tiny monkey bit me and I got tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 3257 times.
Similar Threads
Calculating days between two dates
How to append to a text file for a week
first date and last date of month
Validating date using regex and simple date format
Validating The Date String
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 02:02:50.