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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.