Java 8 引入了一个全新的日期和时间 API,位于 java.time 包中,旨在克服旧版 java.util.Datejava.util.Calendar 的局限性。新的 API 基于  JSR-310 项目,提供了一组不可变且线程安全的日期和时间类。

核心类和接口

以下是一些核心的类和接口:

  • LocalDate:表示没有时区的日期(年、月、日)。
  • LocalTime:表示没有时区的时间(小时、分钟、秒、纳秒)。
  • LocalDateTime:表示没有时区的日期和时间。
  • ZonedDateTime:表示带时区的日期和时间。
  • Period:表示两个日期之间的期间。
  • Duration:表示时间的量,用于计算两个时间之间的差异。
  • Instant:表示时间线上的一点,通常用于生成时间戳。
实践示例
获取当前日期和时间
LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
LocalDateTime currentDateTime = LocalDateTime.now();
ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
Instant currentInstant = Instant.now();

System.out.println("Current Date: " + currentDate);
System.out.println("Current Time: " + currentTime);
System.out.println("Current DateTime: " + currentDateTime);
System.out.println("Current ZonedDateTime: " + currentZonedDateTime);
System.out.println("Current Instant: " + currentInstant);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
创建指定日期和时间
LocalDate dateOfBirth = LocalDate.of(1990, Month.JANUARY, 1);
LocalTime timeOfMeeting = LocalTime.of(13, 30);

System.out.println("Date of Birth: " + dateOfBirth);
System.out.println("Time of Meeting: " + timeOfMeeting);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
日期时间计算
LocalDate tomorrow = LocalDate.now().plusDays(1);
LocalDateTime inTwoWeeks = LocalDateTime.now().plusWeeks(2);
Duration threeMinutes = Duration.ofMinutes(3);
Period fiveDays = Period.ofDays(5);

System.out.println("Tomorrow: " + tomorrow);
System.out.println("In two weeks: " + inTwoWeeks);
System.out.println("Three minutes duration: " + threeMinutes);
System.out.println("Period of five days: " + fiveDays);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
日期时间解析和格式化
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate historicalDate = LocalDate.parse("07/12/1941", formatter);

System.out.println("Historical Date: " + historicalDate);
System.out.println("Formatted Historical Date: " + historicalDate.format(formatter));
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
时区处理
ZonedDateTime zonedDateTime = ZonedDateTime.now();
ZonedDateTime zonedDateTimeInTokyo = zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));

System.out.println("Current ZonedDateTime: " + zonedDateTime);
System.out.println("ZonedDateTime in Tokyo: " + zonedDateTimeInTokyo);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
比较日期和时间
LocalDate independenceDay = LocalDate.of(1945, Month.AUGUST, 17);
LocalDate republicDay = LocalDate.of(1950, Month.JANUARY, 26);

if (independenceDay.isBefore(republicDay)) {
    Period periodBetween = Period.between(independenceDay, republicDay);
    System.out.println("Period between Independence Day and Republic Day: " + periodBetween);
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

新的日期和时间 API 提供了更准确、更易于理解和使用的日期时间处理机制。它解决了旧 API 中存在的线程安全问题,引入了不可变对象,使得日期和时间操作更加安全、简单。通过这些示例,你应该能够开始在你自己的 Java 应用程序中使用这个新的 API 了。