我有以下String格式的时间戳
2019-04-06T00:43:21+00:00
2019-04-04T21:24:33+00:00
2019-04-04T21:02:16+00:00
如何将上面的时间戳字符串解析为Java.sql.timestamp
?
答案 0 :(得分:2)
Timestamp // Avoid this terrible legacy class if possible. Represents a moment in UTC.
.from( // Convert from modern `Instant` to legacy `Timestamp`. No data loss, as both resolve to nanoseconds.
OffsetDateTime // Modern way to represent a moment with an offset-from-UTC (hours, minutes, and seconds).
.parse( "2019-04-06T00:43:21+00:00" ) // Parse standard ISO 8601 strings. Returns a `java.time.OffsetDateTime` object.
.toInstant() // Extract an `Instant` from the `OffsetDateTime`, thereby adjusting to UTC (an offset of zero).
) // Returns a `Timestamp` object, if needed to interoperate with old code not yet updated to *java.time*.
更好的是,完全跳过可怕的Timestamp
类。
myPreparedStatement.setObject( // As of JDBC 4.2 and later, exchange *java.time* objects with your database.
1 , // Specify the nth placeholder in your SQL statement.
OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" ) // Parse an ISO 8601 compliant string as a `OffsetDateTime` object, a moment with an offset-from-UTC. Pass to the database via the `setObject` call.
)
OffsetDateTime
您的输入字符串表示一个offset-from-UTC(时分秒数),该部分在末尾。
您的输入字符串为标准ISO 8601格式。 java.time 类在解析/生成字符串时默认使用这些格式。因此,无需指定格式设置模式。
OffsetDateTime odt = OffsetDateTime.parse( "2019-04-06T00:43:21+00:00" ) ;
java.sql.Timestamp
请勿使用java.util.Timestamp
。可怕的类是几年前被现代的 java.time 类所取代。
如果必须具有Timestamp
对象才能与尚未更新为 java.time 的旧代码进行互操作,请通过调用添加到旧类中的新方法来进行转换。从Instant
中提取OffsetDateTime
(对于UTC本身,从任何偏移量调整为零偏移量)。将Instant
对象传递到Timestamp.from
。
java.sql.Timestamp ts = Timestamp.from( odt.toInstant() ) ;
从JDBC 4.2开始,我们可以与数据库交换 java.time 对象。
myPreparedStatement.setObject( … , odt ) ;
检索。
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
所有这些已经在Stack Overflow上讨论过很多次了。因此,搜索更多信息。将来,请在发布前进行彻底搜索。
java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和SimpleDateFormat
。
要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310。
目前位于Joda-Time的maintenance mode项目建议迁移到java.time类。
您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*
类。
在哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如Interval
,YearWeek
,YearQuarter
和more。
答案 1 :(得分:1)
使用DateFormat解析您的字符串。
try{
String x="2019-04-04T21:24:33+00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssX");
Date date = (Date) df.parse(x);
java.sql.Timestamp timeStamp = new java.sql.Timestamp(date.getTime());
}catch(ParseException pe){
pe.printStackTrace();
}
正如其他人在评论中提到的那样,有一种更新的方法可以做到这一点。
String time="2019-04-04T21:02:16+00:00";
OffsetDateTime odt=OffsetDateTime.parse(time,DateTimeFormatter.ISO_OFFSET_DATE_TIME);
java.sql.Timestamp timestamp=new java.sql.Timestamp(odt.toEpochSecond()*1000);