You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将org.joda.time迁移至java.time并设置时区:代码转换是否正确?

问题解答

首先明确结论:你当前的写法不符合原Joda-Time代码的逻辑,是错误的。

原Joda-Time代码逻辑

startDate.withZoneRetainFields(DateTimeZone.UTC)的核心作用是:保留原时间的年、月、日、时、分、秒等字段值,直接将时区切换为UTC,不做时间点的转换。举个实际例子:

  • 原DateTime是2024-05-20T10:00+08:00(北京时间)
  • 调用该方法后得到的是2024-05-20T10:00Z(UTC时间),时间字段完全保留,仅时区标识变更。

你当前java.time代码的问题

startDate.atZoneSameInstant(ZoneId.of("UTC")).toOffsetDateTime()的作用是:保持原始时间点不变,转换到UTC时区,会自动调整时间字段来匹配UTC的实际时间。用同样的例子验证:

  • 原OffsetDateTime是2024-05-20T10:00+08:00
  • 调用后得到的是2024-05-20T02:00Z,这和原代码的逻辑完全相反。

正确的转换方式

要实现Joda-Time中withZoneRetainFields的逻辑,java.time里针对OffsetDateTime应该使用withOffsetSameLocal方法,直接切换到UTC的偏移量:

private Resource getRegistrations(OffsetDateTime startDate) {
    OffsetDateTime pageStartDate = (startDate == null) ? null : startDate.withOffsetSameLocal(ZoneOffset.UTC);
    return ........;
}

如果入参类型是ZonedDateTime,则对应使用withZoneSameLocal(ZoneId.of("UTC")),再按需转换为OffsetDateTime即可。

内容的提问来源于stack exchange,提问作者Peter Penzov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 22:42:03