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){}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments