Date and Time Difference in JavaNovember 7, 2004Though 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 = Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(elapsed); 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(); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); System.out.println(dateFormat.format(new Date(elapsed))); Does it work? yes.
|
|



