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

在Java中如何使用函数来获取当前时间?

发布时间:2023-06-02 09:00:58

在Java中,可以使用函数来获取当前时间。Java中有两种常用的日期时间类:java.util.Date和java.time包下的类。

1.使用java.util.Date类:

java.util.Date类是Java中最基本的日期时间类。Date类提供了一些方法来获取当前时间,例如:getTime()和toString()方法可以获取毫秒表示的时间和字符串形式的时间。

示例代码:

import java.util.Date;

public class DateDemo {

    public static void main(String[] args) {

        Date date = new Date();

        long time = date.getTime();

        System.out.println(time);

        System.out.println(date.toString());

    }

}

输出结果:

1577982282516

Thu Jan 02 11:57:09 CST 2020

2.使用java.time包下的类:

Java 8中新增了一些日期时间类,放在java.time包中。这些类提供了更多的方法来处理日期和时间,比java.util.Date类更加灵活。以下是java.time包下最常用的类:

- Instant: 表示某个时刻(精确到纳秒)。

- LocalDate: 表示日期(年月日)。

- LocalTime: 表示时间(时分秒毫秒)。

- LocalDateTime: 表示日期和时间。

- ZonedDateTime: 表示日期、时间和时区。

示例代码:

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class LocalDateTimeDemo {

    public static void main(String[] args) {

        LocalDateTime now = LocalDateTime.now();

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

        String nowStr = now.format(formatter);

        System.out.println(nowStr);

    }

}

输出结果:

2021-10-08 21:38:24

总结:

以上就是Java中使用函数获取当前时间的方法。根据实际需求可以选择使用java.util.Date类或java.time包下的类进行时间操作。在实际开发中,需要注意时区和时间格式的问题,以保证时间的准确性和易读性。