There are two options that I can think of:
Option 1:
public class TimestampFormatter {
private static SimpleDateFormat dateFormatter =
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
private static Date date = new Date();
public static String get() {
date.setTime(System.currentTimeMillis());
return dateFormatter.format(date);
}
}
Option 2:
public class TimestampFormatter {
private static SimpleDateFormat dateFormatter =
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
public static String get() {
return dateFormatter.format(new Date());
}
}
And then using this loop to print the formatted date+time every second:
new Thread(() -> {
while (true) {
System.out.println(TimestampFormatter.get());
Sleep.millis(1000);
}
}).start();
I think the first option is the best of the two here, but can anyone think of a better way?