This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes Problem getting correct date format Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem getting correct date format" Watch "Problem getting correct date format" New topic
Author

Problem getting correct date format

Justin Howard
Ranch Hand

Joined: Feb 19, 2009
Posts: 162
Hi All,

It is simple code to convert the date from string format to date format.
When the date is suppose "12/7/2009" it converts correctly
but when I have the string "12/7/09" to convert to date it coverts it to "12/7/0009"
How to get the correct converted date when the input date is "12/7/09"


Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18712
    
    8

But it is working correctly. As the API documentation specifically says:

For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.


If you mean "How do I get the year 09 to be converted to 2009" then continue reading the next paragraph of the SimpleDateFormat API documentation. (There, I provided the link for it.)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19725
    
  20

You could modify the year if it is lower than 100:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Justin Howard
Ranch Hand

Joined: Feb 19, 2009
Posts: 162
Thanks for the implementation Rob.

Paul, Thanks for the explanation and link.

I still had one question though. According to the next paragraph the format "MM/dd/yy" should translate to the current century.
But this code

returns Today = 08/12/06. Why is it like that ?

Thanks for your time.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18712
    
    8

What is the 20th month of 2005?
Justin Howard
Ranch Hand

Joined: Feb 19, 2009
Posts: 162
ok ! .. My bad.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19725
    
  20

You can call setLenient(false) on your DateFormat to have the parse method throw an exception (IllegalArgumentException if I recall correctly) if the year, month or day is out-of-range.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem getting correct date format