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

Viewed 207

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 Answers

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.

Related