I want to print and update the date and time simultaneously. The following code only takes the time once and prints the same time 40 times. How can I update the time while printing it?
public class Dandm {
public static void main(String args[]) {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String time = df.format(date);
int i;
for (i = 40; i > 0; i--) {
System.out.println(date);
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
}
}
Replace System.out.println(date);
with System.out.println(new Date());
The problem is, when you do Date date = new Date();
then date
value doesn't change in the loop. You need a new date every time, so you should create a new Date()
object every time.
Edit based on the comments (To get date as a string with only time):
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
for(i = 40; i > 0; i--){
Date date = new Date();
String str = sdf.format(date);
System.out.println(str);
try{Thread.sleep(500);}
catch (InterruptedException e){}
}
You are creating your object one time only, once your object is created it acquires its properties:
Date date = new Date();
If you want to update your time along side printing it, then either you would create the object within the loop like this:
for (i = 40; i > 0; i--) {
Date date = new Date();
System.out.println(date);
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
Or just create an anonymous Date
object in the print function.
for (i = 40; i > 0; i--) {
System.out.println(new Date());
try {
Thread.sleep(500);
} catch (InterruptedException e){}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With