Why does converting java.util.Date to java.sql.Date result in inaccurate dates?
P粉883278265
P粉883278265 2023-09-01 09:05:06
0
1
416
<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>
P粉883278265
P粉883278265

reply all(1)
P粉237689596

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. html

  • Capital letters Y: Pattern letters representing anniversary
  • Capital letters M: Pattern letters representing months of the year (correct)
  • Capital letters D: Pattern letters representing the number of days in the year

You should use lowercase letters y and lowercase letters d.

  • Lowercase letters y: Pattern letters representing year
  • Lowercase letters d: Pattern letters representing the number of days in the month

I think your conversion should use the following pattern:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template