Calculate elapsed time in Java / Groovy

Viewed 84143

I have...


Date start = new Date()

...
...
...

Date stop = new Date()

I'd like to get the years, months, days, hours, minutes and seconds ellapsed between these two dates.

--

I'll refine the question.

I just want to get the elapsed time, as an absolute measure, that is without taking into account leap years, the days of each month, etc.

Thus I think it's impossible to get the years and months elapsed, all I can get is days, hours, minutes and seconds.

More specifically I want to tell that a certain task lasted for e.g.

20 sec
13 min, 4 sec
2 h, 10 min, 2 sec
4 d, 4 h, 2 min, 2 sec

So please forgive my lack of precision.

16 Answers

You can do all of this with division and mod.

long l1 = start.getTime();
long l2 = stop.getTime();
long diff = l2 - l1;

long secondInMillis = 1000;
long minuteInMillis = secondInMillis * 60;
long hourInMillis = minuteInMillis * 60;
long dayInMillis = hourInMillis * 24;

long elapsedDays = diff / dayInMillis;
diff = diff % dayInMillis;
long elapsedHours = diff / hourInMillis;
diff = diff % hourInMillis;
long elapsedMinutes = diff / minuteInMillis;
diff = diff % minuteInMillis;
long elapsedSeconds = diff / secondInMillis;

That should give you all of the information you requested.

EDIT: Since people seem to be confused, no, this does not take things like leap years or daylight savings time switches into account. It is pure elapsed time, which is what opensas asked for.

Not so easy with the standard Date API.

You might want to look at Joda Time, or JSR-310 instead.

I'm not an expert in Joda, but I think the code would be:

Interval interval = new Interval(d1.getTime(), d2.getTime());
Period period = interval.toPeriod();
System.out.printf(
    "%d years, %d months, %d days, %d hours, %d minutes, %d seconds%n", 
    period.getYears(), period.getMonths(), period.getDays(),
    period.getHours(), period.getMinutes(), period.getSeconds());

Actually, regarding the above answers about Joda-Time.

There's an easier way to do this with Joda-Time’s Period class:

Period period = new Period(startDate, endDate);
System.out.println(PeriodFormat.getDefault().print(period));

To customize the output, look into the PeriodFormat, PeriodFormatter, and PeriodFormatterBuilder classes.

Hmm, if I get what you're asking, you want to know that if:

start = Jan 1, 2001, 10:00:00.000 am and

stop = Jan 6, 2003, 12:01:00.000 pm

you want an answer of 2 years, 0 months, 5 days, 2 hours, 1 minute

Unfortunately, this is a specious answer. What if the dates were Jan 2, and Jan 31? Would that be 29 days? Ok, but Feb 2 to Mar 2 is 28 (29) days, but would be listed as 1 month?

The length of time in anything other than seconds or possibly days is variable without knowing the context since months and years are of different lengths. The difference between 2 dates should be in static units, which are easily computable from stop.getTime() - start.getTime() (which is the difference in millisecs)

import groovy.time.TimeCategory
import groovy.time.TimeDuration

time = { closure ->
    use(TimeCategory) {
        def started = new Date()
        def res = closure()
        TimeDuration duration = new Date() - started
        logger.info("Execution duration: " + duration.toMilliseconds() + "ms")
        res
    }
}

time {
    println 'A realy heavy operation here that you want to measure haha'
}

This is a problem and an algorithm needs to be made to account for leap years and exact amount of months and days beside years. Interesting how it is simple if only one unit of measure is to be used. For example, total number of days between two days is correct as apposed to reminder number of days after number of months and years is calculate within let's say two decades.

I am currently working on this to provide it from my PML implementation, for example, in the form of:

unemployed <- date.difference[
    From = 2009-07-01, 
    Till = now, 
    YEARS, MONTHS, DAYS
]: yyyy-MM-dd

$$-> *unemployed -> date.translate[ YEARS, MONTHS, DAYS ] -> print["Unemployed for:", .]

Of course, this would also be useful and required for exact interest rate calculations.

Related