Course contentsShow
← Java
Lesson 1897 of 2,87038. Date and Time API (java.time)Free lesson

Converting Calendar to ZonedDateTime and LocalDateTime

Extracting Instant from Calendar and converting to appropriate java.time types with time zone information.

Converting Calendar to ZonedDateTime and LocalDateTime

You'll learn how to extract an Instant from a legacy Calendar object and convert it to modern java.time types while preserving time zone information.

The Core Idea

A Calendar object contains both a point in time (like milliseconds since epoch) and a time zone. When migrating to the modern Date and Time API, you can extract the Instant from a Calendar and then apply the time zone information to create either a ZonedDateTime (with full zone rules) or a LocalDateTime (zone-agnostic).

Converting Calendar to ZonedDateTime

import java.util.Calendar;
import java.time.ZonedDateTime;
import java.time.ZoneId;

Calendar calendar = Calendar.getInstance();
calendar.set(2024, Calendar.JANUARY, 15, 14, 30, 0);

// Extract Instant and combine with Calendar's time zone
ZonedDateTime zdt = calendar.toInstant()
    .atZone(calendar.getTimeZone().toZoneId());

System.out.println(zdt); // 2024-01-15T14:30:00-05:00[America/New_York]

The key insight: calendar.toInstant() gives you the moment in time, and calendar.getTimeZone().toZoneId() preserves the original time zone context.

Converting Calendar to LocalDateTime

import java.time.LocalDateTime;

Calendar calendar = Calendar.getInstance();
calendar.set(2024, Calendar.JANUARY, 15, 14, 30, 0);

// Convert via ZonedDateTime, then drop zone info
LocalDateTime ldt = LocalDateTime.ofInstant(
    calendar.toInstant(),
    calendar.getTimeZone().toZoneId()
);

System.out.println(ldt); // 2024-01-15T14:30:00

This preserves the local date-time values in the Calendar's time zone but discards the zone itself.

Key Takeaway: Convert Calendar to modern types by extracting its Instant with toInstant(), then combine with the ZoneId from getTimeZone().toZoneId() to create ZonedDateTime (keeps zone) or LocalDateTime (discards zone but preserves local time).