gpt4 book ai didi

Java 异常之间的持续时间

转载 作者:行者123 更新时间:2023-12-04 22:39:12 26 4
gpt4 key购买 nike

我使用 java Duration between 方法来计算 LocalTime 和 LocalDateTime 之间的持续时间,当我将 localTime 作为方法的第一个参数时它可以工作,但是当我颠倒顺序时,它给出了异常 DateTimeException :

这项工作很好:

 LocalTime t1 = LocalTime.now();
LocalDateTime t2 = LocalDateTime.now();
System.out.println(Duration.between(t1, t2));

当我反转 agrs 时,它给了我一个异常(exception):
 LocalTime t1 = LocalTime.now();
LocalDateTime t2 = LocalDateTime.now();
System.out.println(Duration.between(t2, t1));

Exception in thread "main" java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 16:32:18.553 of type java.time.LocalTime

有人可以解释为什么我得到这个异常感谢任何帮助:=)

最佳答案

来自文档:Duration between

If the objects are of different types, then the duration is calculated based on the type of the first object. For example, if the first argument is a LocalTime then the second argument is converted to a LocalTime.



所以基本上,抛出错误是因为你不能将 LocalTime 对象转换为 LocalDateTime,日期信息不包含在 LocalTime 中。

关于Java 异常之间的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58365280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com