Java Convert Calendar to ZonedDateTime

Tags: Java Calendar Java ZonedDateTime Java 8

In this Java core tutorial we learn how to convert a java.util.Calendar object to a java.time.ZonedDateTime object in Java programming language.

How to convert Calendar to ZonedDateTime in Java

In Java, with a given Calendar object you can follow these steps to convert it to a ZonedDateTime object.

  • Step 1: convert Calendar object to Instant object using Calendar.toInstant() method.
  • Step 2: Use the ZonedDateTime.ofInstant(Instant instant, ZoneId zone) method to convert the above Instant object to ZonedDateTime object in system default time zone.

ConvertCalendarToZonedDateTimeExample1.java

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

public class ConvertCalendarToZonedDateTimeExample1 {
    public static void main(String... args) {
        Calendar calendar = Calendar.getInstance();

        Instant instant = calendar.toInstant();
        ZoneId zoneId = TimeZone.getDefault().toZoneId();
        ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, zoneId);

        System.out.println("Calendar year: " + calendar.get(Calendar.YEAR));
        System.out.println("Calendar month (0 to 11): " + calendar.get(Calendar.MONTH));
        System.out.println("Calendar day of month: " + calendar.get(Calendar.DAY_OF_MONTH));
        System.out.println("Calendar hour: " + calendar.get(Calendar.HOUR_OF_DAY));
        System.out.println("Calendar minute: " + calendar.get(Calendar.MINUTE));
        System.out.println("Calendar second: " + calendar.get(Calendar.SECOND));
        System.out.println("Calendar millisecond: " + calendar.get(Calendar.MILLISECOND));
        System.out.println("ZonedDateTime: " + zonedDateTime);
    }
}
The output as below.
Calendar year: 2022
Calendar month (0 to 11): 4
Calendar day of month: 20
Calendar hour: 0
Calendar minute: 46
Calendar second: 30
Calendar millisecond: 429
ZonedDateTime: 2022-05-20T00:46:30.429+07:00[Asia/Bangkok]

Happy Coding 😊

Java Convert String to LocalDateTime

Java Convert String to LocalTime

Java Convert String to LocalDate

Java Convert Date to ZonedDateTime

Java Convert Date to LocalDateTime

Java Convert Date to LocalTime

Java Convert Calendar to LocalDateTime

Java Convert Calendar to LocalTime