I was having some problem when trying to convert java.util.Date to java.sql.Date. My date parameter passed in was originally a string in this format: 2019-01-31. Then I am trying to convert it to java.util.date using this code:
SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-DD");
Date date = null;
try {
date = formatter.parse(this._dDate);
} catch (ParseException e) {
e.printStackTrace();
}
In my SQL statement, I am trying to convert it to java.sql.Date:
buffer.append("SELECT * FROM TABLE1 WHERE LAST_LOGIN_DT < ");
buffer.append("TO_DATE('" + new java.sql.Date(date.getTime()) + "','YYYY-MM-DD') ");
However, when I printed out the buffer in string, I realized that the date is changed. For instance, the data string I passed in is 2018-01-01, but in the SQL statement it became 2017-12-31. Any ideas?
Thanks!
"yyyy-MM-dd". But don't do this. Go straight from yourStringto yourjava.sql.Date. It will save you a great deal of stress.PreparedStatementinstead of building your SQL via string concatenation. For all sorts of reasons.Dateclasses. They are poorly designed and long outdated. Instead just useLocalDatefrom java.time, the modern Java date and time API. Specificallyselect * from table1 where last_login_dt < ?;andyourPreparedStatement.setObject(LocalDate.parse("2019-01-31"));.