Reputation: 520
I am trying to use the Date class to get the current time each time my loop executes. So far I have:
Date timeNow = new Date();
while(true){
System.out.println(timeNow.getTime()); //prints current time
Thread.sleep(10000);//sleep 10 secounds
}
When the time is reprinted it just shows the same time every print instead of being 10 seconds later. What am I doing wrong? Thanks for the help.
Upvotes: 0
Views: 55
Reputation: 3760
When you execute Date myDate = new Date()
you create a Date
object with the current system time.
Anytime you call myDate.getTime()
you will get the same output, the time as at whenever you created the object.
To see a different time, you would need to create a new Date
object after each Thread.sleep(10000)
, like this:
while(true) {
Date myDate = new Date()
System.out.println(myDate.getTime()); //prints current time
Thread.sleep(10000);//sleep 10 seconds
}
Upvotes: 0
Reputation: 2778
You created timeNow outside of the while loop. The time for this object is captured at construction time. When you move it within the scope of the while loop, you'll get a new object every time which represents the time it was created.
while(true) {
Date timeNow = new Date();
System.out.println(timeNow.getTime()); //prints current time
Thread.sleep(10000);//sleep 10 secounds
}
Note that the default constructor of Date
is equivalent to..
Date timeNow = new Date(System.currentTimeMillis());
Upvotes: 2