Smart objects, not dumb strings
Why use mere text when you can use objects to communicate with your database?
JDBC 4.2
As of JDBC 4.2, we can directly exchange java.time objects with the database. No need to mess with passing strings, or using regex, or calling the Oracle TO_TIMESTAMP
function.
LocalDateTime
For your inputs such as 2017-03-08 10:59:31
, use LocalDateTime
. This class represents a date and a time-of-day lacking any concept of time zone or offset-from-UTC. As such, it is appropriate for database columns of a data type akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE
.
ISO 8601
Your input strings nearly comply with the ISO 8601 standard. Replace the SPACE character in the middle with a T
to fully comply. The java.time class use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Example code
String input = "(1,'Ctx_Log-Log','','08.03.2017','2017-03-08 10:59:31','10:59:32','2017-03-08 10:59:41')";
String inputModified = input.substring( 1 , input.length()-1 ) ; // Remove parens at front and back. In real work, I would check that they are indeed parens.
String[] parts = inputModified.split( "," );
for ( String part : parts ) {
if( part.length()==21 ) { // Possibly a date-time value we are targeting.
String s = part.replace( "'" , "" ); // Remove quote marks.
s = s.replace( " " , "T" ); // To comply with ISO 8601 standard, replace the SPACE in the middle with a `T`.
try {
LocalDateTime ldt = LocalDateTime.parse(s); // Convert string such as `2018-01-23T01:23:45` to a date-time object lacking any concept of time zone or offset-from-UTC.
…
myPreparedStatement.setObject( … , ldt ) ;
…
} catch ( DateTimeParseException e ) {
// Unexpected input.
e.printStackTrace();
}
}
}
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.