The Answer by Jon Skeet is correct but is now outdated in referring to some legacy classes. The java.sql.Date
and java.sql.Timestamp
and related classes are now supplanted by the java.time classes, LocalDate
and Instant
respectively. But your Question demands the LocalDateTime
class.
Smart objects, not dumb strings
You objects to represent your date-time values. As of JDBC 4.2 and later, you can directly exchange java.time objects with your database.
Your inputs lack any indicator of time zone or offset-from-UTC. So parse in Java as a LocalDateTime
for storage in a column of a type similar to SQL-standard TIMESTAMP WITHOUT TIME ZONE
.
DateTimeFormatter f1 = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
DateTimeFormatter f2 = DateTimeFormatter.ofPattern( "dd-MM-uu HH:mm:ss" ) ;
DateTimeFormatter f3 = DateTimeFormatter.ofPattern( "dd-MM-uu HH:mm" ) ;
Choose a formatter by length of the input string.
LocalDateTime ldt = LocalDateTime.parse( myInputString , f2 ) ;
I need to build the SQL by hand as the user defines the criteria, compare operators and joins in the user interface. In the end I have something like this
String sqlSnippet = "TO_DATE('" + sFormat.format(date) + "','DD-MM-YYYY HH24:MI:SS')";
No, do not embed your date-time value as text in a String of SQL. Instead, use a PreparedStatement
with ?
placeholders replaced with your LocalDateTime
object.
String sql = "SELECT when FROM tbl WHERE when > ? ;" ;
Pass the object to be slipped into that placeholder at runtime.
myPreparedStatement.setObject( … , ldt ) ;
Retrieval:
LocalDateTime ldt = myResultSet.getObject( … ; LocalDateTime.class ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.