I want to show the system time and the seconds counting in real time in Java.
I want to show the system time and the seconds counting in real time in Java.
You can use the Java service scheduler to display the times every second.
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.*;
public class Relogio {
public static void main(String args[]) throws IOException {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()));
}
}, 1, 1, TimeUnit.SECONDS);
}
}
There is no need to use the Thread
class, nor use the sleep
method, nor make any exception handling.
According to this answer in SO can do this:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Thread th = new Thread(new Runnable() { //cria uma thread
public void run() {
while(true) { //roda indefinidamente
Date date = Calendar.getInstance().getTime(); //pega a hora do sistema
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
String today = formatter.format(date);
System.out.println(today);
try {
Thread.sleep(1000); //espera 1 segundo para fazer a nova evolução
} catch(InterruptedException ex){
//é algo terrível a se fazer mas pelo jeito a API medonha do Java exige
}
}
}
});
th.start();
}
}
It may not give the best result but that's it. There are no guarantees that all screen updates will occur every 1 second accurate.
You have to position the cursor always in the same position but since I can not test, I'll just leave the code for you to try:
System.out.print(String.format("%c[%d;%df", 0x1B, 0, 0));
I think this is what you want
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JLabel;
public class relogio {
public static void main(String[] args) {
try {
while (true) {
Date d = new Date();
StringBuffer data = new StringBuffer();
SimpleDateFormat sdfData = new SimpleDateFormat("dd.MM.yyyy");
data.append(sdfData.format(d));
data.append(" - ");
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(""+data.toString() + sdf.format(d));
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println("Problema na atualização da data/hora");
ex.printStackTrace();
}
}
}