回答編集履歴
1
取得した日時との差分でやるバージョンを追記
answer
CHANGED
@@ -16,4 +16,32 @@
|
|
16
16
|
}
|
17
17
|
}, 0, 1000);
|
18
18
|
}
|
19
|
+
```
|
20
|
+
|
21
|
+
元々の質問は、重複する原因と対策だと思いますが、
|
22
|
+
載せられているコードを実行しても、1秒毎に表示されることもなく、
|
23
|
+
全く動いてないように見えたので、質問者さんのコードを参考にしたバージョンも書いてみました。
|
24
|
+
```Java
|
25
|
+
import java.time.LocalDateTime;
|
26
|
+
import java.time.format.DateTimeFormatter;
|
27
|
+
import java.time.temporal.ChronoUnit;
|
28
|
+
|
29
|
+
public class Sample {
|
30
|
+
private static final int LIMIT = 20;
|
31
|
+
public static void main(String[] args) throws Exception {
|
32
|
+
int counter = 0;
|
33
|
+
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd hh:mm:ss");
|
34
|
+
LocalDateTime previous = LocalDateTime.now();
|
35
|
+
while (true) {
|
36
|
+
LocalDateTime now = LocalDateTime.now();
|
37
|
+
if (ChronoUnit.MILLIS.between(previous, now) >= 1000) {
|
38
|
+
previous = now;
|
39
|
+
System.out.println(now.format(formatter));
|
40
|
+
if (++counter == LIMIT) {
|
41
|
+
break;
|
42
|
+
}
|
43
|
+
}
|
44
|
+
}
|
45
|
+
}
|
46
|
+
}
|
19
47
|
```
|