java.time
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Solution using modern date-time API:
- Parse the date-time string into
LocalDateTime
:
String dateAndTime = "5/23/14 02:23:24";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/uu H:m:s", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(dateAndTime, dtf);
- Set the instance of
LocalDateTime
into the database using PreparedStatement#setObject
:
Statement st = conn.createStatement();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, ldt);
st.executeUpdate();
st.close();
- In order to read it from the database, use
Resultset#getObject
:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE ...");
while (rs.next()) {
LocalDateTime ldt = rs.getObject(1, LocalDateTime.class));
System.out.println(ldt);
}
rs.close();
st.close();
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.