Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the interval between two java.util.date [duplicate]

Possible Duplicate:
Calculating the Difference Between Two Java Date Instances

hi, I have two object of type java.util.date.

Date StartDate; Date EndDate;

Both object have a date and specified time. I need to find the interval between them in hours, minutes and seconds. I can do it in someways but i was thinking that my technique is not the best.

So what tech would u have used for this operation in Java

like image 533
Noor Avatar asked Dec 30 '10 19:12

Noor


People also ask

How do you check if a date is in between 2 dates in Java?

We can use the simple isBefore , isAfter and isEqual to check if a date is within a certain date range; for example, the below program check if a LocalDate is within the January of 2020. startDate : 2020-01-01 endDate : 2020-01-31 testDate : 2020-01-01 testDate is within the date range.

How can I compare two dates in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.

How can I get the difference between two dates in Java 8?

Using JodaTime, you can get the difference between two dates in Java using the following code: Days d = Days. daysBetween(startDate, endDate). getDays();


2 Answers

The most basic approach would use something like:

long interval = EndDate.getTime() - StartDate.getTime();

you'll get the number of milliseconds between the events. Then it's a matter of converting that into the hours, minutes and seconds.

like image 167
dhable Avatar answered Sep 28 '22 11:09

dhable


JodaTime can handle this stuff for you. See, in particular, Interval and Period.

import org.joda.*;
import org.joda.time.*;

// interval from start to end
DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2005, 1, 1, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println(period.getYears() + " years, " + period.getMonths() + " months, " + period.getWeeks() + " weeks, " + period.getDays() + ", days");

The above will print: 0 years, 0 months, 1 weeks, 0 days

like image 22
Brian Clapper Avatar answered Sep 28 '22 13:09

Brian Clapper