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);
To calculate the number of hours between two dates we can simply subtract the two values and multiply by 24.
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")
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With