Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top