将 java.util.Calendar ISO 8601 格式转换为 java.sql.Timestamp
Convert java.util.Calendar ISO 8601 format to java.sql.Timestamp
我有一个 ISO 8601 日期格式的日期 2015-09-08T01:55:28Z
。我使用此代码将 ISO 8601 命运转换为日历对象:
Calendar cal = javax.xml.bind.DatatypeConverter.parseDateTime("2015-09-08T01:55:28Z");
现在我需要使用 cal.getTime()
来获取我的时间,但我需要将其转换为 java.sql.Timestamp
。我尝试这样做:
final Timestamp finalDate = (Timestamp) cal.getTime();
但是我得到了这个错误:
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Timestamp
想法?
如异常所述:Calendar::getTime()
returns a java.util.Date
object, not a java.sql.Timestamp
对象。所以你不能将它转换为 Timestamp 对象。
使用:
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
并考虑替换 Java SE 8 中引入的 Calendar
with the new Date & Time API。
Puce 的 是正确的。
java.time
Java 8 及更高版本中的现代方法是使用新的 java.time 框架。这些新的 classes 取代了旧的 java.util.Date/.Calendar,后者已被证明是令人困惑和麻烦的。
Instant
是时间轴上的一个时刻,从 1970 年第一时刻开始的纳秒计数(UTC)。 class 能够解析像您这样符合 ISO 8601 格式的字符串。
String input = "2015-09-08T01:55:28Z";
Instant instant = Instant.parse( input );
旧 java.sql
类型的数据库
从 Instant 中,我们可以得到一个新添加到这个旧 class 的 java.sql.Timestamp by calling the from
方法。
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
我们可以将所有三行合并为一行,我不推荐这样做(使调试更加困难)。
java.sql.Timestamp ts = Timestamp.from( Instant.parse( "2015-09-08T01:55:28Z" ) );
数据库通过 java.time
类型
截至 JDBC 4.2, a compliant JDBC driver should be able to pass the java.time types via getObject
and setObject
on a PreparedStatement
。如果您的驱动程序不支持,请使用旧 classes 的转换方法。
myPreparedStatement.setObject( 1 , instant );
我有一个 ISO 8601 日期格式的日期 2015-09-08T01:55:28Z
。我使用此代码将 ISO 8601 命运转换为日历对象:
Calendar cal = javax.xml.bind.DatatypeConverter.parseDateTime("2015-09-08T01:55:28Z");
现在我需要使用 cal.getTime()
来获取我的时间,但我需要将其转换为 java.sql.Timestamp
。我尝试这样做:
final Timestamp finalDate = (Timestamp) cal.getTime();
但是我得到了这个错误:
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Timestamp
想法?
如异常所述:Calendar::getTime()
returns a java.util.Date
object, not a java.sql.Timestamp
对象。所以你不能将它转换为 Timestamp 对象。
使用:
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
并考虑替换 Java SE 8 中引入的 Calendar
with the new Date & Time API。
java.time
Java 8 及更高版本中的现代方法是使用新的 java.time 框架。这些新的 classes 取代了旧的 java.util.Date/.Calendar,后者已被证明是令人困惑和麻烦的。
Instant
是时间轴上的一个时刻,从 1970 年第一时刻开始的纳秒计数(UTC)。 class 能够解析像您这样符合 ISO 8601 格式的字符串。
String input = "2015-09-08T01:55:28Z";
Instant instant = Instant.parse( input );
旧 java.sql
类型的数据库
从 Instant 中,我们可以得到一个新添加到这个旧 class 的 java.sql.Timestamp by calling the from
方法。
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
我们可以将所有三行合并为一行,我不推荐这样做(使调试更加困难)。
java.sql.Timestamp ts = Timestamp.from( Instant.parse( "2015-09-08T01:55:28Z" ) );
数据库通过 java.time
类型
截至 JDBC 4.2, a compliant JDBC driver should be able to pass the java.time types via getObject
and setObject
on a PreparedStatement
。如果您的驱动程序不支持,请使用旧 classes 的转换方法。
myPreparedStatement.setObject( 1 , instant );