Why does converting java.util.Date to java.sql.Date result in inaccurate dates?
P粉883278265
2023-09-01 09:05:06
<p>I am converting java.util.Date to java.sql.date in order to insert date of birth into mysql database. </p>
<p>However, entering <code>2001-04-03</code> always results in <code>java.sql.Date</code> being <code>2000-12-31</code> </p>
<pre class="brush:java;toolbar:false;">BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter dob(YYYY-MM-DD) :");
String date = br.readLine();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
java.util.Date util_dob = dateFormat.parse(date);
java.sql.Date dob = new java.sql.Date(util_dob.getTime());
</pre>
<p>Enter: 2001-04-03</p>
<p>Output: 2000-12-31</p>
<p>Expectation: 2001-04-03</p>
Your format string is incorrect.
Please view the documentation for
SimpleDateFormat
: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat. htmlYou should use lowercase letters y and lowercase letters d.
I think your conversion should use the following pattern: