温馨提示×

JAVA中如何实现显示当前时间

小亿
104
2023-11-10 14:04:24
栏目: 编程语言

在Java中,可以使用java.util.Date类和java.text.SimpleDateFormat类来实现显示当前时间。

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

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

运行上述代码,将会输出当前时间的字符串表示,格式为yyyy-MM-dd HH:mm:ss,例如:“2022-01-01 12:34:56”。

0