简体   繁体   中英

util.date to sql.date giving the wrong date

String d = request.getParameter("date");
SimpleDateFormat dateFormat = new SimpleDateFormat("mm-dd-yyyy"); 
java.util.Date utilDate = dateFormat.parse(d);
java.sql.Date date = new java.sql.Date(utilDate.getTime());

The above code is to get a date from a form and get it into sql.date format to use in a prepared statement, however the date being produced is wrong, 03-14-2012 is being converted to 2012-01-14 +00:00:00

Am i doing this the right way?

Your DateFormat is incorrect mm are minutes, MM are months.

Regards

As burna has said, your date formatting is incorrect. For a full list of formats, refer to: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

As you can see, months are defined by MM. For a Month-Day-Year date, you should be looking at the format: "MM-dd-yyyy" Hope that helps.

The problem is not with the call to the java.sql.Date constructor. If you print out utilDate you will see that the value is already wrong at that point.

The issue is your SimpleDateFormat string - it should be "MM-dd-yyyy", that is, with the M's capitalized. See the javadoc for all the conversion codes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM