在使用Java8之前,我使用了Joda的DateTime类来包含时区信息,并且可以很容易地在DateTime和Timestamp之间进行转换。
一旦迁移到Java8,我应该替换哪个类?OffsetDateTime还是ZonedDateTime
此外,我尝试使用OffsetDateTime,但它似乎不能从sql Timestamp构造回OffsetDateTime。
对于Joda DateTime和Timestamp转换器,代码如下:
val joda = DateTime.now()
val sqlJoda = new Timestamp(joda.getMillis)
val jodaBack = new DateTime(sqlJoda)但对Java8来说,
val java8 = OffsetDateTime.now()
val sqlJava8 = new Timestamp(java8.toInstant.toEpochMilli)
val java8Back = ???有谁知道这一点吗?看起来Joda DateTime真的很棒。
发布于 2016-01-05 18:36:07
您可以使用ZonedDateTime。下面是我用来来回转换为Timestamp的一些示例代码。
public ZonedDateTime from(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
final ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.of("UTC"));
return zonedDateTime;
}
public Timestamp to(ZonedDateTime zonedDateTime) {
if (zonedDateTime == null) {
return null;
}
final Timestamp timestamp = Timestamp.valueOf(zonedDateTime.withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime());
return timestamp;
}请注意,我以UTC格式将日期时间存储在数据库中。
发布于 2016-01-05 18:25:34
使用java.time中的Java8API,您可以执行以下操作:
long ms_since_epoch = 1_500_000_000_000L;
Instant instant = Instant.ofEpochMilli(ms_since_epoch);
// convert milliseconds in UTC to date
OffsetDateTime dateUTC = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);使用您的约定:
val java8 = OffsetDateTime.now()
val sqlJava8 = new Timestamp(java8.toInstant.toEpochMilli)
val java8Back = OffsetDateTime.ofInstant(sqlJava8.toInstant(), ZoneOffset.UTC);发布于 2016-01-05 19:46:43
我假设您的数据库类型是timestamp with time zone。如果它是一个timestamp without timezone,你将需要一个不同的类型/转换机制。
JDBC 4.2 spec建议将timestamp with time zone映射到OffsetDateTime。下面是如何在OffsetDateTime和java.sql.Timestamp之间进行转换。
从OffsetDateTime到Timestamp的
时间戳ts = ...;ZoneId.systemDefault());
Timestamp to OffsetDateTime:时间戳ts = Timestamp.from(odt.toInstant());;OffsetDateTime odt =...
https://stackoverflow.com/questions/34609225
复制相似问题