Finding an interval between two java.util.date

Possible duplicate:
Calculating the difference between two instances of Java dates

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

Date StartDate; Date EndDate;

Both objects have a date and a specified time. I need to find the interval between them in hours, minutes and seconds. I can do it differently, but I thought that my technique is not the best.

So what technologies would you use for this operation in Java

+7
source share
2 answers

The simplest approach would be to use something like:

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

you will get the number of milliseconds between events. Then it is a matter of turning it into hours, minutes and seconds.

+12
source

JodaTime can process this material 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 week, 0 days

+8
source

All Articles