I am converting java.util.Date to java.sql.date to insert date of birth in mysql database.
But entering 2001-04-03 always results in a java.sql.Date of 2000-12-31
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());
input: 2001-04-03
output: 2000-12-31
expecting: 2001-04-03
SimpleDateFormatand the twoDateclasses. They are troublesome and hacky, nothing you want to struggle with, and fortunately all long outdated. UseLocalDatefrom java.time, the modern Java date and time API.LocalDate.parse(date). You can directly pass the resultingLocalDateto your SQL database. See Insert & fetch java.time.LocalDate objects to/from an SQL…String date = "2001-04-03";and leave output reading from input. You might also print thejava.util.Datesince this would demonstrate the problem, and you would not need to convert tojava.sql.Datefor this. If this was your first question, you are doing really good.