Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Working in Java time

Learn the basics of calculating elapsed time in Java

  • Print
  • Feedback

Page 2 of 6

long milliseconds = 1999;
long seconds = 1999 / 1000;


That way of converting milliseconds to seconds eliminates fractions, so 1,999 milliseconds equals 1 second, while 2,000 milliseconds equals 2 seconds.

To calculate larger units -- such as days, hours, and minutes -- given a number of seconds, you can use the following process:

  1. Calculate the largest unit, reducing the number of seconds accordingly
  2. Calculate the next largest unit, reducing the number of seconds accordingly
  3. Repeat until only seconds remain


For example, if your elapsed time is 10,000 seconds, and you want to know how many hours, minutes, and seconds that value corresponds to, you start with the largest value: hours. Divide 10,000 by 3,600 (seconds in an hour) to calculate the number of hours. Using integer division, the answer is 2 hours (fractions are dropped in integer division). To calculate the remaining seconds, reduce 10,000 by 3,600 times 2 hours: 10,000 - (3,600 x 2) = 2,800 seconds. So you have 2 hours and 2,800 seconds.

To convert 2,800 seconds to minutes, divide 2,800 by 60 (seconds per minute). With integer division, the answer is 46. And 2,800 - (60 x 46) = 40 seconds. The final answer is 2 hours, 46 minutes, and 40 seconds.

The above calculation is shown in the following Java program:

import java.util.*;
public class Elapsed1 {
   public void calcHMS(int timeInSeconds) {
      int hours, minutes, seconds;
      hours = timeInSeconds / 3600;
      timeInSeconds = timeInSeconds - (hours * 3600);
      minutes = timeInSeconds / 60;
      timeInSeconds = timeInSeconds - (minutes * 60);
      seconds = timeInSeconds;
      System.out.println(hours + " hour(s) " + minutes + " minute(s) " + seconds + " second(s)");
   }
   public static void main(String[] args) {
      Elapsed1 elap = new Elapsed1();
      elap.calcHMS(10000);
   }
}  


Output from the above program is:

  • Print
  • Feedback

Resources
  • Also by Robert Nielsen: