This is probably not advanced enough for this forum, but..
I'm trying to get a "clock" to work out in java (actually as a JSP, but for now, in Java). When I execute the following code, I get the same time over and over, but I (thought) am reloading the time value at every iteration of the loop...
The getTime() method returns the time as represented when the date object was created, not the current time. It never updates unless you update its attributes in your code.
You can think of this as an object representing a time, not an API object to access the time if that makes sense.
Try this:
private void clock() { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
while(true) { Date d = new Date(); System.out.print(df.format(d));
you may wish to replace the while(true) stuff with Thread.sleep(x) or some other sleeping mechanism where x is the number of milliseconds you wish to sleep. Your code will be processor intensive (just looping like that)
Take a look at Timer. Use that to fire an update once every second. In the interest of accuracy I would update by getting the actual time, not by increasing some variable by one to indicate on second. Reason being you're less likely to have small errors in time cumulate.
Thanks for the responses.. I haven't really had to code in a while, so I'm trying to catch back up. I'll let you know what I wind up with.
As a general review question: Won't the "new Date()" call cause a bunch of Date objects in memory? If so, when can they be expired to be collected by the garbage collector or would that really matter?
Thanks again. Sam [ August 21, 2006: Message edited by: Sam Smoot ]