欢迎访问宙启技术站
智能推送

如何在Java中使用函数来获取当前时间并格式化输出?

发布时间:2023-06-30 12:58:26

在Java中,可以使用java.time包提供的LocalDateTime类来获取当前时间,并使用DateTimeFormatter类来格式化输出时间。

首先,需要导入java.timejava.time.format包:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

然后,可以使用LocalDateTime.now()方法获取当前时间。LocalDateTime类表示了不带时区的日期和时间信息。

LocalDateTime now = LocalDateTime.now();

接下来,可以使用DateTimeFormatter类创建一个格式化时间的实例。可以使用ofPattern方法指定时间的格式,如"yyyy-MM-dd HH:mm:ss"表示年-月-日 时:分:秒。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

然后,可以使用format方法将LocalDateTime对象格式化成指定的字符串形式。

String formattedNow = now.format(formatter);
System.out.println("当前时间:" + formattedNow);

完整的示例代码如下:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        System.out.println("当前时间:" + formattedNow);
    }
}

运行该代码,即可获取当前时间并以指定格式输出。

注意:在使用format方法时,如果参数为null或格式不正确,会抛出NullPointerExceptionDateTimeParseException异常,可以根据需要进行异常处理。