Hi, I'm making my first attempts to work in
Java with time issues.
I'm just wondering if there is a "direct" method to print a long
elapsed time in milliseconds in a hh:mm:ss.ms format. Also, see the
question at the end of the code sample. Thanks.
Here is a sample code:
import java.util.*;
public class TimeAndDate
{
public static void main(
String[] args)
{
Calendar calendar = new GregorianCalendar();
Date trialTime = new Date();
long start = trialTime.getTime();
calendar.setTime(trialTime);
System.out.println("Started at: " +
calendar.get(calendar.HOUR_OF_DAY)+":"+
calendar.get(Calendar.MINUTE)+":"+
calendar.get(Calendar.SECOND)+"."+
calendar.get(Calendar.MILLISECOND));
//Make some time between start time and end time:
for (int i=1; i<200000000; i++){}
trialTime = new Date();
long end = trialTime.getTime();
calendar.setTime(trialTime);
System.out.println("Ended at: "+
calendar.get(calendar.HOUR_OF_DAY)+":"+
calendar.get(Calendar.MINUTE)+":"+
calendar.get(Calendar.SECOND)+"."+
calendar.get(Calendar.MILLISECOND));
long elapsed = end-start;
System.out.println(elapsed + " elapsed milliseconds.");
trialTime.setTime(elapsed);
calendar.setTime(trialTime);
int seconds = (int) elapsed / 1000;
int milliSeconds = (int) elapsed % 1000;
int minutes = seconds / 60;
seconds = seconds % 60;
int hours = minutes / 60;
minutes = minutes % 60;
System.out.println(
hours + " hours, " + minutes + " minutes, " +
seconds + " seconds, " + milliSeconds + " ms elapsed.");
//Why is the result of this statement wrong???
System.out.println("Elapsed time: "+
calendar.get(calendar.HOUR_OF_DAY)+":"+
calendar.get(Calendar.MINUTE)+":"+
calendar.get(Calendar.SECOND)+"."+
calendar.get(Calendar.MILLISECOND));
}
}
Here is a sample output:
------------------------
Started at: 7:52:16.990
Ended at: 7:52:21.820
4830 elapsed milliseconds.
0 hours, 0 minutes, 4 seconds, 830 ms elapsed.
Elapsed time: 19:0:4.830
Question: Why is it showing 19 hours elapsed? Somehow it added 12 hours.
Thanks in advance folks!
P.s.: is there a "timer" class in the API?