I do not really understand what you are trying to achieve. Parsing user input into a Date? Storing a Date into a MySQL DB field of type date (or datetiteme/timestamp) as an object or as a string?
1. Parsing user input
The code you propose parses user input into a java.util.Date correctly provided that the input is indeed in the expected format:
String dateimput="24/12/2009"; // Christmas Eve
java.text.DateFormat df = new java.text.SimpleDateFormat("dd/MM/yyyy");
java.util.Date dt = null;
try
{
dt = df.parse(dateimput);
System.out.println("date imput is:" +dt);
// = "date imput is:Thu Dec 24 00:00:00 CET 2009"
}
catch (java.text.ParseException e)
{
e.printStackTrace();
}
Notice that when a Date knows nothing about the format used for parsing it and outputting it as you do ('...+dt') calls its toString(), which by default uses the long date format. However there is no reason why that should be a problem for you. If you want to log it in a particular format, follow Daniel's suggestions.
2. Storing the date to the DB
If you store the date into a date /datetime/timestamp field via JDBC you have two options:
(A) Using string query and a Statement
Construct the insert query as a String and pass it to a Statement as in:
aConnection.createStatement().executeUpdate(
"insert into mytable(mydate) values(" + df.format(dt) + ")")
In this case you must make sure that the date string is in a format the DB can understand (such as yyyy-mm-dd for DB2).
(B) Using a PreparedStatement
Or, which is must safer because it prevents SQL injection, and also easier because it delegates the conversion of java types to the proper database form to the DB's JDBC driver, use a prepared statement:
PreparedStatement pstmt = con.prepareStatement(
"insert into mytable(mydate) values(?)");
pstmt.setDate(1, new java.sql.Date(dt.getTime()))