Convert java.util.Calendar ISO 8601 format to java.sql.Timestamp

扶醉桌前 提交于 2021-02-04 23:56:30

问题


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?


回答1:


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.




回答2:


The Answer by Puce is correct.

java.time

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 );

Database via old java.sql types

From 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" ) );

Database via java.time types

As 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 );


来源:https://stackoverflow.com/questions/32461307/convert-java-util-calendar-iso-8601-format-to-java-sql-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!