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

计算两个DateTime分钟间隔时抛出UnsupportedTemporalTypeException异常求助

解决java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds异常

错误原因

你用LocalDate类解析包含时分秒的日期字符串,但LocalDate仅代表日期(年-月-日),不包含时分秒等时间维度信息。而Duration.between()方法用于计算两个带时间的时间点之间的间隔,它依赖时、分、秒这类时间单位进行计算,传入仅含日期的LocalDate会触发不支持秒单位的异常。

修正后的代码

public long datetimeDiffInMinutes(String dateStop, String dateStart) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    // 改用LocalDateTime解析包含时分秒的字符串
    LocalDateTime firstDateTime = LocalDateTime.parse(dateStart, formatter);
    LocalDateTime secondDateTime = LocalDateTime.parse(dateStop, formatter);
    Duration d1 = Duration.between(firstDateTime, secondDateTime);
    long min = d1.toMinutes();
            
    return min;
}

补充说明

  • LocalDateTime是包含日期+时间的类型,完全匹配你使用的yyyy-MM-dd HH:mm:ss格式,能正确解析时分秒信息,满足分钟级间隔计算的需求。
  • 若仅需计算两个日期的整天数间隔,才适合用LocalDate搭配ChronoUnit.DAYS.between()方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:24:21