两个 Date 实例之间的小时差会抛出 “结束时间必须大于开始时间” 异常。

huangapple go评论54阅读模式
英文:

difference of two Date instance in hours throws "The end instant must be greater the start" exception

问题

我想找出两个日期之间的小时差异。

我尝试使用 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 2019date2=Mon Jul 01 12:30:00 IST 2019 时,会抛出异常:

Exception: java.lang.IllegalArgumentException: The end instant must be greater the start

请解释一下造成这个问题的原因以及如何修复。我正在使用 Java 8。

英文:

I want to find the difference between two Dates in terms of hours.

I tried using 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();
	}

but this throws exception when date1=Mon Jul 01 08:30:00 IST 2019 and date2=Mon Jul 01 12:30:00 IST 2019

Exception:java.lang.IllegalArgumentException: The end instant must be greater the start

Please explain to me what is the reason and how I can fix this. I am using Java 8.

答案1

得分: 2

你可以使用持续时间 API 来计算持续时间(找到天数/分钟/小时)

Math.abs(Duration.ofMillis(endTime).minusMillis(startTime).toHours())

在答案中进行了编辑,因为结束时间可能早于开始时间,但在尝试之前,始终请检查结束时间和开始时间。

英文:

You can use the duratin api for the duration ( find the days/ minutes/ hours )

Math.abs( Duration.ofMillis(endTime).minusMillis(StartTime).toHours())

Edited the answer as the endtime you may pass less than the start time, but always try to check the endtime and start time before trying.

huangapple
  • 本文由 发表于 2020年8月27日 18:55:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/63614514.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定