Java print date and time of every input

83 Views Asked by At

I want an output of something like this

hi 2022.11.06 12:08:50 pm
hello 2022.11.06 12:09:40 pm

but I keep getting

hi 2022.11.06 12:08:50 pm
hello 2022.11.06 12:08:50 pm

even though I do the next input after a time interval.

Scanner reader = new Scanner(System.in);

Date dNow = new Date();
SimpleDateFormat dtformat = new SimpleDateFormat ("yyyy.MM.dd hh:mm:ss a");

for (int x = 0; x <= 5; x++){ 
    String obj = reader.nextLine();
    System.out.println(obj + dtformat.format(dNow));
}

I want an output of something like this

hi 2022.11.06 12:08:50 pm
hello 2022.11.06 12:09:40 pm
1

There are 1 best solutions below

2
On

Java is, like most programming languages, imperative.

int x = 5;
int y = x;

does not mean that 'y' is an alias for 'x'. It simply means: Resolve the expression x, and take whatever that currently resolves to, then update the value of y to be that value. Resolving expression x simply means: What is the current value of this variable.

in other words:

int x = 5;
int y = x;
x = 4;
System.out.println(y);

This prints 5. It does not print 4.

In your code, you resolve the expression new Date() exactly once, at the very start, and never again. dNow is set in stone once you ran it, and doesn't update. Simply rerun dNow = new Date(); to update.

NB: This is obsolete, broken API; you should be using the java.time package types, such as LocalDateTime, and the java.time formatters (DateTimeFormatter). The old stuff conflates human reckoning with computer reckoning, and thus fails when timezone definitions change. Which they do, every day.