Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Parsing date using SimpleDateFormat for hh mm ss

 
Gaurav Kr. Arora
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

My program is shown below:


In this program if my input date string is "12/03/1956 12:34:99", then also I am getting valid date in sysout.
Output: Valid new date is :Mon Dec 03 12:34:00 IST 1956

My requirement is to show date invalid to user if in input seconds are supplied. My input is valid if it is 12/03/1956 12:34, else invalid if it contains seconds information.
How can I achieve it without using substrings, regex? I can only use SimpleDateFormat.

Thanks.
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, you don't need to re-format the Date to show only the year and then parse that to an int. You can use a Calendar for that:
Now, to the problem at hand. This is one of the reasons I don't like the parse(String) methods. They allow trailing characters after the valid input. By using the other parse method, parse(String, ParsePosition), you can prevent this. An added benefit is that you don't need to catch a ParseException:
The parse(String) method only checks for validity. This also checks if the current parse position is directly at the end of the input. If it isn't then there are characters after the valid date.
 
Gaurav Kr. Arora
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the timely help! :-)
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
Gaurav Kr. Arora
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One more doubt.

I have string like "January2011" which can be validated using "MMMMMyyyy" pattern. But, "MMMMMyyyy" pattern will validate "Jan2011" which I don't want.
I can use parse position and the way suggested in above posts, but since my code is generic and am validating other patterns also, I can't do it.

So, is it possible to validate fullmonthYYYY with any pattern in java without using parse position and checking the length of pattern?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic