I have a date in ISO 8601 date format 2015-09-08T01:55:28Z
. I used this code to convert the ISO 8601 fate to a Calendar object:
Calendar cal = javax.xml.bind.DatatypeConverter.parseDateTime("2015-09-08T01:55:28Z");
and now I need to use the cal.getTime()
to get my time, but I need to convert it to a java.sql.Timestamp
. I tried to do this:
final Timestamp finalDate = (Timestamp) cal.getTime();
but I got this error:
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Timestamp
Ideas?
We can convert date to timestamp using the Timestamp class which is present in the SQL package. The constructor of the time-stamp class requires a long value. So data needs to be converted into a long value by using the getTime() method of the date class(which is present in the util package).
ISO 8601 is an international standard covering the worldwide exchange and communication of date and time-related data. It is maintained by the Geneva-based International Organization for Standardization (ISO) and was first published in 1988, with updates in 1991, 2000, 2004, and 2019, and an amendment in 2022.
Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss. fffffffff , where ffffffffff indicates nanoseconds.
As the exception says: Calendar::getTime()
returns a java.util.Date
object, not a java.sql.Timestamp
object. So you cannot cast it to a Timestamp object.
Use:
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
And also consider to replace Calendar
with the new Date & Time API introduced in Java SE 8.
The Answer by Puce is correct.
The modern way in Java 8 and later is to use the new java.time framework. These new classes supplant the old java.util.Date/.Calendar that have proven to be confusing and troublesome.
An Instant
is a moment on the timeline, a count of nanoseconds from first moment of 1970 in UTC. The class is able to parse strings such as yours that comply with the ISO 8601 format.
String input = "2015-09-08T01:55:28Z";
Instant instant = Instant.parse( input );
java.sql
typesFrom an Instant, we can get a java.sql.Timestamp by calling the from
method newly added to this old class.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
We could combine all three lines into a one-liner, not that I recommend it (makes debugging more difficult).
java.sql.Timestamp ts = Timestamp.from( Instant.parse( "2015-09-08T01:55:28Z" ) );
java.time
typesAs of JDBC 4.2, a compliant JDBC driver should be able to pass the java.time types via getObject
and setObject
on a PreparedStatement
. If your driver does not, use the conversion methods for the old classes.
myPreparedStatement.setObject( 1 , instant );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With