How to write code in Java to display the current time?

To display the current time in Java, you can use the classes java.util.Date and java.text.SimpleDateFormat.

Below is an example code that displays the current time in the format “yyyy-MM-dd HH:mm:ss”:

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

public class CurrentTime {
    public static void main(String[] args) {
        // 创建一个Date对象,表示当前时间
        Date now = new Date();
        
        // 创建一个SimpleDateFormat对象,指定时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        // 使用SimpleDateFormat对象格式化Date对象,得到时间字符串
        String currentTime = sdf.format(now);
        
        // 输出时间字符串
        System.out.println("当前时间:" + currentTime);
    }
}

The above code will output results similar to the following content:

当前时间:2022-01-01 12:34:56

You can adjust the time format as needed, for example: “yyyy/MM/dd HH:mm:ss”, “yyyy年MM月dd日 HH时mm分ss秒”, etc.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds