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

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

发布时间:2023-06-10 17:26:03

Java 中获取当前时间并格式化输出的方法有很多种,下面介绍两种常用的方式。

一、使用 SimpleDateFormat 类

SimpleDateFormat 是 java.text 包下的一个类,可以将 Date 类型的数据格式化成指定的格式。下面是使用 SimpleDateFormat 类获取当前时间并格式化输出的示例代码:

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

public class Test {

    public static void main(String[] args) {
        // 创建 SimpleDateFormat 对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 获取当前时间
        Date date = new Date();
        // 格式化输出
        System.out.println(sdf.format(date));
    }

}

上面的代码中,我们先创建了一个 SimpleDateFormat 对象,指定了时间的输出格式为 yyyy-MM-dd HH:mm:ss,然后调用 Date 类的无参构造方法获取当前时间,并通过 sdf 对象的 format 方法将时间格式化成指定的格式输出。

二、使用 DateTimeFormatter 类

DateTimeFormatter 是 java.time.format 包下的一个类,是 Java 8 中新增的时间处理方式。DateTimeFormatter 类提供的操作比 SimpleDateFormat 类更加简单,同时也支持时区等常见的操作。下面是使用 DateTimeFormatter 类获取当前时间并格式化输出的示例代码:

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

public class Test {

    public static void main(String[] args) {
        // 创建 DateTimeFormatter 对象
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化输出
        System.out.println(dtf.format(now));
    }

}

上面的代码中,我们先创建了一个 DateTimeFormatter 对象,指定了时间的输出格式为 yyyy-MM-dd HH:mm:ss,然后调用 LocalDateTime 类的 now 方法获取当前时间,并通过 dtf 对象的 format 方法将时间格式化成指定的格式输出。

总结:

以上就是两种使用 Java 获取当前时间并格式化输出的方法。虽然这两种方式实现的效果相似,但 DateTimeFormatter 类拥有更多的操作,同时也是 Java 8 中官方推荐的时间处理方式,因此建议使用 DateTimeFormatter 类。