Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem getting correct date format

 
Justin Howard
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21319
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could modify the year if it is lower than 100:
 
Justin Howard
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21319
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the 20th month of 2005?
 
Justin Howard
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok ! .. My bad.
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic