說明

Use java.time (LocalDate, LocalDateTime, ZonedDateTime) instead of java.util.Date or java.sql.Date. The old date API is mutable, not thread-safe, and hard to work with.

為什麼重要

  • Thread safetyjava.time classes are immutable
  • Correctness — explicit timezone handling prevents DST bugs
  • API clarityLocalDate.of(2024, 1, 15) is self-documenting

Enforcement

SE_BAD_FIELD — non-serializable field in serializable class (Date is poorly serialised)

Remediation

mvn rewrite:run -DactiveRecipe=org.openrewrite.java.migrate.time.UseJava8TimeClasses

正例

public class Order {
    private final LocalDateTime createdAt;
    private final LocalDate expectedDelivery;

    public Order(LocalDateTime createdAt, LocalDate expectedDelivery) {
        this.createdAt = createdAt;
        this.expectedDelivery = expectedDelivery;
    }
}

反例

public class Order {
    private Date createdAt;        // ❌ mutable, not thread-safe
    private Date expectedDelivery; // ❌ ambiguous: is this date-only or datetime?
}