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

咨询将org.joda.time.Duration迁移至java.time.Duration的正确实现方式

Joda 迁移至 java.time API 解决方案

问题分析

你在改写endTimerProcess方法时误用了Duration.of(),该方法需要的是时长数值+时间单位(比如Duration.of(5, ChronoUnit.SECONDS)),而非两个Instant对象,这才导致了参数类型不匹配的错误。

正确迁移代码

完整修正后的代码

import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;

private OffsetDateTime createdDate;
private Duration executionTime;
private Instant requestTime;

public void startTimerProcess() {
    this.requestTime = Instant.now();
}

public void endTimerProcess() {
    // 用Duration.between()替代Joda的new Duration(start, end)
    this.executionTime = Duration.between(requestTime, Instant.now());
}

关键迁移点说明

  • Duration的创建:Joda中new Duration(Instant start, Instant end)对应java.time的Duration.between(Temporal startInclusive, Temporal endExclusive),该方法专门用于计算两个时间点之间的时长。
  • createdDate的类型替换:Joda的DateTime如果是带时区偏移的,用OffsetDateTime是合理的;如果原DateTime绑定了完整时区(比如Asia/Shanghai),建议改用ZonedDateTime更贴合原语义。
  • Instant的使用:java.time的Instant和Joda的Instant语义完全一致,都是表示UTC时间线上的瞬时点,Instant.now()的用法可直接兼容。

内容的提问来源于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:17:18