温馨提示×

java怎么显示实时时间

小亿
96
2024-05-31 09:56:11
栏目: 编程语言

在Java中显示实时时间可以使用java.util.Date类和java.text.SimpleDateFormat类。以下是一个简单的示例代码:

import java.util.Date;
import java.text.SimpleDateFormat;

public class ShowRealTime {
    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        while(true) {
            Date currentTime = new Date();
            String currentTimeStr = dateFormat.format(currentTime);
            System.out.println("Current time: " + currentTimeStr);
            
            try {
                Thread.sleep(1000); // 每隔1秒更新一次时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在上面的代码中,我们创建了一个SimpleDateFormat对象来指定时间的格式,并在一个无限循环中不断获取当前时间并显示出来。通过调用Thread.sleep(1000)方法来让程序每隔1秒更新一次时间。

运行上面的代码,您将看到实时时间以指定的格式显示在控制台上。

0