harqs
harqs

Reputation: 177

Calculating difference in two time

I am calculating the difference between two times and i am able to get the difference in hours and minuted using separate equations,is there any single equation from which i can get hours and minutes at one go.I am using like:

here diff is the difference between two time value

long diffHours1 = diff / (60 * 60 * 1000);
long min=diff/(60*1000);

Upvotes: 3

Views: 447

Answers (4)

Eran Medan
Eran Medan

Reputation: 45735

I'm not sure it is helpful here, but Joda Time seems to have a little more verbose solution using Period e.g.

Period p = new Period(startDate, endDate)
int minutes = p.getMinutes(); //returns the left over minutes part
int seconds = p.getSeconds(); //returns the seconds part

I'm not sure that for this particular case you need something else than what you have, I agree with aix's

Upvotes: 5

Thomas
Thomas

Reputation: 88707

Well, two equations are not that bad (actually using more lines makes it easier to read), although you might change the order, correct the equation and cache some results.

diff = //time difference in milliseconds
long diffInMinutes = diff / (60 * 1000);    

//get the number of hours, e.g. 140 / 60 = 2
long hours = diffInMinutes  / 60;

//get the left over minutes, e.g. 140 % 60 = 20
long minutes = diffInMinutes  % 60;   

If the reason you want one equation is ease of use, try using an alternative library like Joda Time.

Upvotes: 1

Crazenezz
Crazenezz

Reputation: 3456

Yes there is:

String oneGo = (diff / (60 * 60 * 1000)) + " " + (diff / (60 * 1000));

:-)

Upvotes: 1

NPE
NPE

Reputation: 500357

is there any single equation from which i can get hours and minutes at one go

No, not easily. A Java expression can only have one result; returning several things is not impossible, but would require additional machinery (a wrapper class, a tuple etc). This would result in code that's significantly more complicated than what you have right now.

What you can do to simplify things a little bit is compute minutes first, and then compute hours based on minutes:

long diffMinutes = diff / (60*1000);
long diffHours = diffMinutes / 60;

Upvotes: 1

Related Questions