views:

53

answers:

2

Hi, I need to set a date field in my html form. After submitting the form the request goes to the servlet and tha data will be stored in database. In servlets how can i retrieve the date field? Please help me.

-renu

+2  A: 

You'll get it out of the HttpRequest parameters:

DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
String dateAsString = httpRequest.getParameter("form-name-for-the-date-here");
Date dateAsObject = dateFormatter.parse(dateAsString);

If you're using Spring you should use their data binding API.

duffymo
A: 

The above answer is good. If you want to change your format at database level use this format.

In PreparedStatement:

  • For MySQL TIMESTAMP use to_timestamp( ? ,'dd-mm-yyyy %h:%i:%s') format.
  • For Oracle TIMESTAMP use to_date(dateAsString ,'DD-MM-RR HH24:MI:SS') format.
  • For MySQL DATE use to_timestamp( ? ,'dd-mm-yyyy') format.
  • For Oracle DATE use to_date(? ,'DD-MM-RR') format.

Set dateAsString in PreparedStatement.

String dateAsString = httpRequest.getParameter("form-name-for-the-date-here");
Parag
I wouldn't massage date forth and back as string. This is a performance pain whenever you want to select rows by date. E.g. between certain timestamps, or months or days, etc. Use the right type for the value!
BalusC
@paragjioshi, why don't you simply use `PreparedStatement.setDate()` method? The vendors who implements the database driver will have optimised ways to store dates in their respective database servers. All this conversion is unecessary.
The Elite Gentleman