tags:

views:

208

answers:

4

I have two Date objects and I need to get the time difference so I can determine the total hours between them. They happen to be from the same day. The result I would like would have the hours and minutes.

When I use .toString() on my Date object I get this: Fri Dec 18 08:08:10 CST 2009

I've tried the following:

long diff=(this.endDate.getTime()-this.startDate.getTime())/(60*60 * 1000);

But this only gives me hours, not the minutes. I know this is a simple problem, but I can't figure it out atm.

Edits: Final solution for those interested. Thanks to Michael Brewer-Davis

Period p = new Period(this.startDate, this.endDate);
long hours = p.getHours();
long minutes = p.getMinutes();

String format = String.format("%%0%dd", 2);

return Long.toString(hours)+":"+String.format(format, minutes);
A: 

So the getTime() method, I presume, returns an integer.

In which case, the left set of parentheses has type int, right?

and

(60*60*1000)

is also an int.

Which means you get long diff = ((int)/(int)) so the integer division is done BEFORE you cast stuff to long. And hence you lose your minutes.

Try casting them BEFORE you divide.

piggles
The getTime() method returns a Long not an int.
clang1234
Ah... Then what Rob Van Dam said, I think. Also what Gregs said.
piggles
A: 

let x = the difference in milliseconds. x / (1000*60*60) to get hours,x % (1000*60*60) to get the remainder in milliseconds. Now divide the remainder by 1000*60 to get the minutes, and take the remainder mod (1000*60) to get the remainder of the remainder in milliseconds. Keep going if you want to get seconds, etc.

GregS
+4  A: 

This should work.

long secs = (this.endDate.getTime() - this.startDate.getTime()) / 1000;
int hours = secs / 3600;    
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;
Rob Van Dam
+5  A: 

Here's how it works with Joda time:

DateTime startTime, endTime;
Period p = new Period(startTime, endTime);
long hours = p.getHours();
long minutes = p.getMinutes();

You could format with Joda's formatters, e.g., PeriodFormat, but I'd suggest using Java's. See this question for more details.

Michael Brewer-Davis
This is just about perfect. Thanks for the Joda Time link. But how to I get the display to be "H:mm" where H is hours and m minutes. For example "1:05". At the moment is would display "1:5"
clang1234
Added a formatting link for you.
Michael Brewer-Davis
Wonderful. Thanks for the help
clang1234