Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

time validation  RSS feed

 
Rodney Hirokane
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Set the leniency of your DateFormat to false.
 
W. Joe Smith
Ranch Hand
Posts: 710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 .
 
Rodney Hirokane
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for all who replied. My code now works using setLenient as Rob mentioned.

Rod
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!