问题
In my JSP page I have a field which is date and when I getting as request.getParameter("dateVal");
gives me
15-Dec-2012 12:21.
I would like to pass this value to my database procedure and insert/update into table.
How can I pass the value as setDate
using prepareCall
to database?
Thanks
回答1:
First step would be using SimpleDateFormat to parse it to a fullworthy java.util.Date instance in the controller:
Date date = new SimpleDateFormat("dd-MMM-yyyy HH:mm.", Locale.ENGLISH).parse(dateVal);
Then you can just create a java.sql.Date around its time in the database layer:
statement.setDate(1, new java.sql.Date(date.getTime()));
Unrelated to the concrete problem, please note that java.sql.Date
doesn't remember the time part. If you have actually a DATETIME
or TIMESTAMP
field in the DB and not a DATE
field, then rather use setTimestamp()
with a java.sql.Timestamp
instead. This way the time part will also be stored.
回答2:
@BalusC 's answer is perfect. But as an alternative solution you can use the function provided by database to convert String to Date while querying. For example(in case you use Oracle),
to_date(date_in_String, format)
回答3:
Try this :
new SimpleDateFormat("dd-MM-yyyy HH:mm").parse(mydate);
来源:https://stackoverflow.com/questions/12896295/request-getparameter-string-value-pass-as-date-to-java