Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

date or calendar object creation

 
Peter Guillebaud
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, how do you make a calendar or a date object from a string variable like "1 Jan 2001"? I want to use this object in a sql query against a microsoft sql database with a datetime column.
many thanks
 
Peter Guillebaud
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I try this code
String myDate = "1 Jan 2001";
GregorianCalendar gc = new GregorianCalendar();
DateFormat df = DateFormat.getDateInstance( DateFormat.SHORT );gc.setTime( df.parse( myDate ) );
but it gives exception:
javax.servlet.ServletException: Unparseable date: "1 Jan 2001"
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you consult the documentation, you will see that DateFormat.SHORT is expected to be completely numeric, so obviously it is not a good candidate here. DateFormat.MEDIUM is more likely to work for you, but it depends on the Local used, and the exact format used is not documented. Your best best is to use SimpleDateFormat instead:
<pre>DateFormat df = new SimpleDateFormat("dd MMM yyyy");</pre>
This allows you to more explicitly control the format used.
 
Peter Guillebaud
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks very much Jim
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic