简体   繁体   English

util.date给sql.date提供错误的日期

[英]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 上面的代码是从表单中获取日期并将其转换为sql.date格式以在预准备语句中使用,但是生成的日期是错误的,03-14-2012正在转换为2012-01-14 +00 :00:00

Am i doing this the right way? 我这样做是对的吗?

Your DateFormat is incorrect mm are minutes, MM are months. 你的DateFormat不正确mm是分钟,MM是几个月。

Regards 问候

As burna has said, your date formatting is incorrect. 正如burna所说,你的日期格式是不正确的。 For a full list of formats, refer to: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html 有关格式的完整列表,请参阅: http//docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

As you can see, months are defined by MM. 如您所见,MM定义了几个月。 For a Month-Day-Year date, you should be looking at the format: "MM-dd-yyyy" Hope that helps. 对于一个月 - 日 - 年的日期,你应该看看格式: "MM-dd-yyyy"希望有所帮助。

The problem is not with the call to the java.sql.Date constructor. 问题不在于调用java.sql.Date构造函数。 If you print out utilDate you will see that the value is already wrong at that point. 如果您打印出utilDate,您将看到该值已经错误。

The issue is your SimpleDateFormat string - it should be "MM-dd-yyyy", that is, with the M's capitalized. 问题是你的SimpleDateFormat字符串 - 它应该是“MM-dd-yyyy”,即M的大写字母。 See the javadoc for all the conversion codes. 有关所有转换代码,请参阅javadoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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