search

Home  >  Q&A  >  body text

Why does converting java.util.Date to java.sql.Date result in inaccurate dates?

<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粉883278265P粉883278265470 days ago424

reply all(1)I'll reply

  • P粉237689596

    P粉2376895962023-09-02 00:55:05

    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");
    

    reply
    0
  • Cancelreply