Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find total hours between two Dates

Tags:

java

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); 
like image 523
clang1234 Avatar asked Jan 05 '10 01:01

clang1234


People also ask

How do I calculate the number of hours between two dates?

To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.

How do I calculate hours between two dates in Excel?

Formula 2. Calculate hours between two times: =TEXT(B2-A2, "h") Return hours and minutes between 2 times: =TEXT(B2-A2, "h:mm") Return hours, minutes and seconds between 2 times: =TEXT(B2-A2, "h:mm:ss")


1 Answers

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; 
like image 69
Rob Van Dam Avatar answered Sep 17 '22 11:09

Rob Van Dam