File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Calculating Elapsed Time Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Calculating Elapsed Time " Watch "Calculating Elapsed Time " New topic

Calculating Elapsed Time

Nikki Freeman

Joined: Nov 03, 2005
Posts: 10
I have more of a math problem than I java problem.

I need to calculate the elapsed time bettween two Calendars. Most of the posts that I have found show how to find the elapsed time in milliseconds and then do simple math on the determined difference.

I need to figure out how to get the elapsed days, hours, and minutes for a given difference. ie:

start time: 1/30/08 2:30 PM - end time:01/30/08 07:34 AM
0 days 6 hours 56 minutes.

here is where I'm at:

Any thoughts on where I am going wrong?
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

Once you have the number of days as difference / 86400000, then the remainder (which you want to break down into hours and so on) is difference % 86400000.

However you have a completely different error, namely assuming that each day is 24 hours. That isn't the case in many places. For example where I live we have daylight saving time, so one day in the spring has only 23 hours and one day in the autumn has 25 hours. If you don't care about that then carry on with your calculation. If you do care about it (and you probably should for real-life applications) then you need to let the Calendar class take care of those details. Something like this:
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46407
Find the TimeUnit enumerated type in the standard Java API, and read about that. It might help change milliseconds to days, etc. It might also have constants like MILLISECONDS_IN_DAY. I am not sure; I haven't used it for a long time.

The difference in milliseconds is difference % MILLISECONDS_IN_SECOND
The difference in seconds is difference % MILLISECONDS_IN_MINUTE / SECONDS_IN_MINUTE.
etc etc.
Just beware: you might get very strange results with the % operator if the original argument is negative!
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46407
Paul Clapham and I seem to agree about the % operator and nothing else. Just goes to show there are usually several equally valid ways to do anything on a computer.
I agree. Here's the link:
subject: Calculating Elapsed Time
It's not a secret anymore!