Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to update Date and Time in a loop

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){}
        }
    }
}

2 Answers

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){}
}
like image 153
Atri Avatar answered Oct 16 '25 22:10

Atri


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){}
}
like image 43
Tayyab Kazmi Avatar answered Oct 16 '25 21:10

Tayyab Kazmi