Legacy Date Calendar Interop Conversion

Bridge java.util.Date and Calendar to java.time through Instant and toInstant so old APIs and new code exchange the same moment losslessly.

JavaConfig Management

Code

snippet
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class LegacyInterop {

    public static void main(String[] args) {
        // 旧 API 产出 java.util.Date
        Date legacy = new Date(0L);

        // Date -> Instant:旧类型交给新代码
        Instant moment = legacy.toInstant();
        System.out.println("epoch: " + moment.equals(Instant.EPOCH));

        // Instant -> Date:新代码把结果传回旧 API
        Date back = Date.from(Instant.parse("2026-11-18T09:30:00Z"));
        System.out.println("millis: " + back.getTime());

        // Calendar 同样通过 Instant 桥接:Calendar.toInstant() 读取
        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        cal.setTimeInMillis(back.getTime());
        Instant fromCalendar = cal.toInstant();
        System.out.println("calendar: " + fromCalendar);

        // LocalDateTime 没有时区,转 Instant 必须显式给出偏移
        LocalDateTime naive = LocalDateTime.of(2026, 11, 18, 9, 30);
        Instant withOffset = naive.toInstant(ZoneOffset.UTC);
        System.out.println("naive + UTC: " + withOffset.equals(fromCalendar));
    }
}

How the snippet works

Everything happens inside the class LegacyInterop and the function main.

What to watch for

  • The imports (if any) point only at standard-library modules.

Applying it

Entry signature: public static void main(String[] args)

Output lines are prefixed (epoch:, millis:, calendar:), keeping the output trace and the executing steps in one-to-one view.

Statements that matter

Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
Date back = Date.from(Instant.parse("2026-11-18T09:30:00Z"));
LocalDateTime naive = LocalDateTime.of(2026, 11, 18, 9, 30);

Interactive Tools for This Topic

FAQ

What does Legacy Date Calendar Interop Conversion print when run?
No setup needed: run the file and look for labeled lines like `epoch:`, `millis:`, `calendar:` in the output.