我有以下代码,它们使用Joda时间库从sql Timestamp对象获取偏移量。
public static long getOffset(Chronology chronology_, Timestamp timeStamp_)
{
long offset = 0;
if (chronology_ != null)
{
offset = chronology_.getZone().getOffset(new DateTime(timeStamp_).getMillis());
}
return offset;
}
如何使用Java 8 API实现相同的目的。我不确定是否需要按时间顺序排列。
虽然时序的Joda-Time概念和时序的java.time(JSR-310)概念相似,但在您所处的情况中存在重要的区别:Joda-Time Chronology
可能(可选)具有时区。 java.time.chrono.Chronology
不能。因此,您需要以不同于时序的其他方式提供用于操作的时区。
现在,我们可以建议您也通过java.sql.Timestamp
以外的其他方式提供时间点。因此,一种选择是:
public static long getOffset(ZoneId zone, Instant when)
{
long offset = 0;
if (zone != null)
{
int offsetSeconds = zone.getRules()
.getOffset(when)
.getTotalSeconds();
offset = TimeUnit.SECONDS.toMillis(offsetSeconds);
}
return offset;
}
如果您的呼叫者从他们无法更改的旧版API中获得了老式Timestamp
,则应进行转换。因此,调用上述方法的一种方法是:
long offsetMillis = getOffset(
ZoneId.of("Africa/Khartoum"), theirTimesatmp.toInstant());
System.out.println(offsetMillis);
从现在开始使用时间戳的示例输出:
7200000
Timestamp
类的设计不当,是对本来就设计不当的java.util.Date
类的一种真正的破解,所以我们不应该使用它。如果无法避免,请立即将其转换为Instant
或LocalDateTime
,然后从那里执行或进行进一步的工作。
如果您确实坚持提供接受Timestamp
的便捷方法,则您当然可以添加一个对过去友好的包装器。例如:
/** @deprecated use {@link #getOffset(ZoneId, Instant)} instead */
public static long getOffset(ZoneId zone, Timestamp timeStampParam)
{
return getOffset(zone, timeStampParam.toInstant());
}
[Link: Stephen Colebourne博客上的Converting from Joda-Time to java.time