Java 提供了丰富的日期时间处理功能,主要集中在 `java.time` 包下。`java.time` 包是从 Java 8 开始引入的,设计用于解决旧的 `java.util.Date` 和 `java.util.Calendar` 类存在的问题,提供了更加清晰、易用和线程安全的 API。
### 主要类和接口
1. **LocalDate**: 表示日期,例如 `2024-07-15`。
 2. **LocalTime**: 表示时间,例如 `14:43:35`。
 3. **LocalDateTime**: 表示日期和时间,例如 `2024-07-15T14:43:35`。
 4. **ZonedDateTime**: 表示带时区的日期和时间。
 5. **Instant**: 表示时间戳,通常用于机器时间。
 6. **Duration**: 表示时间段。
 7. **Period**: 表示日期段。
### 示例代码
```java
 import java.time.LocalDate;
 import java.time.LocalTime;
 import java.time.LocalDateTime;
 import java.time.format.DateTimeFormatter;
public class DateTimeExample {
     public static void main(String[] args) {
         // 获取当前日期
         LocalDate currentDate = LocalDate.now();
         System.out.println("当前日期: " + currentDate); // 输出格式:2024-07-15
        // 获取当前时间
         LocalTime currentTime = LocalTime.now();
         System.out.println("当前时间: " + currentTime); // 输出格式:14:43:35.123456789 (具体时间会有微秒部分)
        // 获取当前日期和时间
         LocalDateTime currentDateTime = LocalDateTime.now();
         System.out.println("当前日期和时间: " + currentDateTime); // 输出格式:2024-07-15T14:43:35.123456789
        // 格式化日期时间
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
         String formattedDateTime = currentDateTime.format(formatter);
         System.out.println("格式化后的日期时间: " + formattedDateTime); // 输出格式:2024-07-15 14:43:35
        // 解析字符串到日期时间
         String dateTimeString = "2023-12-25 10:30:00";
         LocalDateTime parsedDateTime = LocalDateTime.parse(dateTimeString, formatter);
         System.out.println("解析后的日期时间: " + parsedDateTime); // 输出格式:2023-12-25T10:30
        // 演示 Duration 和 Period
         LocalDateTime start = LocalDateTime.of(2023, 1, 1, 10, 0);
         LocalDateTime end = LocalDateTime.of(2023, 1, 1, 11, 30);
         Duration duration = Duration.between(start, end);
         System.out.println("时间段: " + duration); // 输出格式:PT1H30M
        LocalDate date1 = LocalDate.of(2023, 1, 1);
         LocalDate date2 = LocalDate.of(2024, 1, 1);
         Period period = Period.between(date1, date2);
         System.out.println("日期段: " + period); // 输出格式:P1Y
        // 更复杂的时区操作需要使用 ZonedDateTime
         // ZonedDateTime zonedDateTime = ZonedDateTime.of(...);
     }
 }
 ```
### 总结
Java 的 `java.time` 包提供了强大且易于使用的日期时间处理功能,支持格式化、解析、计算时间段和日期段等操作,使得在处理日期时间时更加方便和安全。通过合理利用这些类和方法,可以有效避免传统 `java.util.Date` 和 `java.util.Calendar` 类所带来的问题。