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.

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:

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
Sheriff

Joined: Oct 13, 2005
Posts: 40508

28

posted

0

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.