您的位置:

Java.time:Java中全新的日期和时间处理API

Java 8中引入了全新的日期和时间API,即Java.time包。与以前的Java.util包和Java.sql.Date不同,Java.time是为了在可以处理不同时间标准、时间精度和时区中提供更好的支持而创建的。

一、LocalDate和LocalTime类

Java.time包中最基本的类是LocalDate和LocalTime。其中LocalDate表示日期,LocalTime表示时间。


// 现在的日期和时间
LocalDate today = LocalDate.now();
LocalTime currentTime = LocalTime.now();

System.out.println(today); // 2021-04-20
System.out.println(currentTime); // 13:43:25.309202200

如果你想获取一个特定日期的值,可以使用of()方法。例如,下面展示了如何获取生日的日期:


LocalDate birthday = LocalDate.of(1990, 5, 26);

你还可以使用get()方法获取特定日期的部分值,例如获取年、月、日等。


int year = birthday.getYear();
int month = birthday.getMonthValue();
int day = birthday.getDayOfMonth();

System.out.println(year); // 1990
System.out.println(month); // 5
System.out.println(day); // 26

二、LocalDateTime类

LocalDateTime类是LocalDate和LocalTime的组合体,表示日期和时间。你可以使用now()方法获取当前日期和时间。


LocalDateTime currentDateTime = LocalDateTime.now();

System.out.println(currentDateTime); // 2021-04-20T14:05:53.172504800

你还可以使用of()方法创建特定的日期和时间。


LocalDateTime dateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 0, 0);

三、ZonedDateTime类

ZonedDateTime类是一个日期时间的完整表示,包括时区信息。你可以使用now()方法获取当前日期和时间以及时区信息。


ZonedDateTime currentDateTimeWithZone = ZonedDateTime.now();

System.out.println(currentDateTimeWithZone); // 2021-04-20T14:14:31.233656-04:00[America/New_York]

你还可以使用of()方法创建特定的日期和时间以及时区信息。


ZoneId zoneId = ZoneId.of("America/Los_Angeles");
ZonedDateTime dateTimeWithZone = ZonedDateTime.of(2022, 1, 1, 12, 0, 0, 0, zoneId);

System.out.println(dateTimeWithZone); // 2022-01-01T12:00-08:00[America/Los_Angeles]

四、Duration和Period类

Duration和Period类是用于处理时间段的类。Duration用于表示两个时间之间的时间量,而Period用于表示两个日期之间的天数、月数或年数差异。


LocalDateTime dateTime1 = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 0, 0);
LocalDateTime dateTime2 = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 30, 0);

Duration duration = Duration.between(dateTime1, dateTime2);

System.out.println(duration); // PT30M

LocalDate date1 = LocalDate.of(1990, 5, 26);
LocalDate date2 = LocalDate.of(2022, 1, 1);

Period period = Period.between(date1, date2);

System.out.println(period); // P31Y7M6D

五、DateTimeFormatter类

DateTimeFormatter类用于格式化和解析日期和时间。它的格式化和解析方法与SimpleDateFormat类似,但有更好的线程安全性。

例如,要将日期格式化为字符串,可以使用如下代码:


LocalDateTime dateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 0, 0);

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

String formattedDateTime = dateTime.format(formatter);

System.out.println(formattedDateTime); // 2022-01-01 12:00:00

相反,要将字符串解析为日期,可以使用如下代码:


String dateTimeString = "2022-01-01 12:00:00";

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

LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, formatter);

System.out.println(parsedDateTime); // 2022-01-01T12:00

六、总结

本文介绍了Java 8中的Java.time包,包括LocalDate和LocalTime类、LocalDateTime类、ZonedDateTime类、Duration和Period类以及DateTimeFormatter类。通过这些类,Java开发人员可以更好地处理日期和时间,并在时间标准、时间精度和时区之间自如地穿梭。