Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate elapsed time in Java / Groovy

Tags:

java

date

groovy

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.

like image 647
opensas Avatar asked Feb 19 '09 23:02

opensas


People also ask

How do I use TimeCategory in groovy?

Using TimeCategory make DateTime manipulation simpler than using regular Java time/date API. Like the previous tutorial, we will use web Groovy executor to run our Groovy codes. Open your browser and go to Groovy Console. Next, just paste your code inside code box then click execute.


1 Answers

I've just discovered this quick Groovy-sourced solution:

import groovy.time.TimeCategory  import groovy.time.TimeDuration  Date start = new Date()  // do something here  Date stop = new Date()  TimeDuration td = TimeCategory.minus( stop, start ) println td 
like image 188
pd. Avatar answered Sep 19 '22 14:09

pd.