I\'m trying to convert the following string \"2012-04-13 04:08:42.794\"
to a date type:
SimpleDateFormat dateFormat = new SimpleDateFormat(\
myPreparedStatetment.setObject(
… ,
LocalDateTime.parse(
"2012-04-13 04:08:42.794".replace( " " , "T" )
)
)
The Answer by SJuan76 is correct: You are being fooled by the poorly-designed output of the Date::toString
method. Instead, use java.time classes.
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes such as Date
/Calendar
.
First convert your input string to fully comply with the ISO 8601 standard. Replace the SPACE in the middle with a T
.
String input = "2012-04-13 04:08:42.794".replace( " " , "T" ) ;
Parse as a LocalDateTime
since your input lacks an indicator of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2012-04-13T04:08:42.794
Avoid the date-time related java.sql
classes. They too are supplanted by the java.time classes. As of JDBC 4.2, you can directly exchange java.time objects with your database. So you can forget all about the java.sql.Date
class and its terrible hacked design.
myPreparedStatement.setObject( … , ldt ) ;
And…
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
Moral of the story # 1: Use smart objects, not dumb strings.
Moral of the story # 2: Use only java.time objects. Avoid legacy date-time classes.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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.