溫馨提示×

java怎么顯示實時時間

小億
186
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女