开发者

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

This question already has answers h开发者_StackOverflow社区ere: Closed 12 years ago.

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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜