gpt4 book ai didi

java - 以小时为单位的两个 Date 实例的差异引发 "The end instant must be greater the start"异常

转载 作者:行者123 更新时间:2023-12-04 08:59:51 28 4
gpt4 key购买 nike

我要找两个日期之间的小时差异 .
我尝试使用 Joda-Time API:

public static long getDateTimeDiffInHours(Date  date1, Date  date2) {
Interval interval = new Interval(date2.getTime(), date1.getTime());
Duration period = interval.toDuration();
return period.getStandardHours();
}
但这会在 date1=Mon Jul 01 08:30:00 IST 2019 和 date2=Mon Jul 01 12:30:00 IST 2019 时引发异常
Exception:java.lang.IllegalArgumentException: The end instant must be greater the start
请向我解释是什么原因以及如何解决此问题。我正在使用 Java 8。

最佳答案

您可以在持续时间内使用 duratin api(查找天/分钟/小时)

Math.abs( Duration.ofMillis(endTime).minusMillis(StartTime).toHours())
将答案编辑为您可能通过的结束时间少于开始时间,但在尝试之前始终尝试检查结束时间和开始时间。

关于java - 以小时为单位的两个 Date 实例的差异引发 "The end instant must be greater the start"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63614514/

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