Date and Time Difference in Java

November 7, 2004

Though I have been a programmer for 17 years I have never quite got the hang of date/time calculation in any of the programming language I know (I can assure you there are quite a few). Recently I needed to calculate the time elapsed since a thread was started and here is what I came up with first:


long startTime = Calendar.getInstance().getTimeInMillis();
.....

SimpleDateFormat dateFormat =
new SimpleDateFormat("HH:mm:ss");

Calendar cal = Calendar.getInstance();
elapsed = cal.getTimeInMillis() - startTime;

cal.setTimeInMillis(elapsed);
System.out.println(dateFormat.format(cal.getTime()));


If you think that's a feeble attempt you are right. It does not even work as expected. It prints out 05:29:00 where it should say 00:00:00 and counts upwards from 05:29:00. What's the reason? timezone.

After reading the documentation (with a total lack of comphrehension) and scratching around with this for more than 30 minutes my brain finally started to function and I came up with this:


long startTime = System.currentTimeMillis();
....

long currentTime = System.currentTimeMillis();
SimpleDateFormat dateFormat =
new SimpleDateFormat("HH:mm:ss");

dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
elapsed = currentTime - startTime;

System.out.println(dateFormat.format(new Date(elapsed)));

Does it work? yes.

Posted by raditha at November 7, 2004 10:57 AM
Your Ad Here

 

Jabber  |  Linux  |  mySQL  |  PHP  |  Java  |  Site Map  |  Wiki

Downloads  |  About  |  Links  |  Contact  |  Home

 

Copyright © Raditha Dissanayake 2003 - 2007

Terms of Use  |  Privacy

 

 

November 2004
Sun Mon Tue Wed Thu Fri Sat
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30