Java Convert Calendar to LocalDateTime
Tags: Java Calendar Java LocalDateTime Java 8
In this Java core tutorial we learn how to convert a java.util.Calendar object to a java.time.LocalDateTime object in Java programming language.
How to convert Calendar to LocalDateTime in Java
In Java, with a given Calendar object you can follow these steps to convert it to a LocalDateTime object.
- Step 1: convert Calendar object to Instant object using Calendar.toInstant() method.
- Step 2: Use the LocalDateTime.ofInstant(Instant instant, ZoneId zone) method to convert the above Instant object to LocalDateTime object in system default time zone.
ConvertCalendarToLocalDateTimeExample1.java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.TimeZone;
public class ConvertCalendarToLocalDateTimeExample1 {
public static void main(String... args) {
Calendar calendar = Calendar.getInstance();
Instant instant = calendar.toInstant();
ZoneId zoneId = TimeZone.getDefault().toZoneId();
LocalDateTime localDateTime = LocalDateTime.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("LocalDateTime: " + localDateTime);
}
}
Calendar year: 2022
Calendar month (0 to 11): 4
Calendar day of month: 20
Calendar hour: 0
Calendar minute: 40
Calendar second: 46
Calendar millisecond: 312
LocalDateTime: 2022-05-20T00:40:46.312
Happy Coding 😊
Related Articles
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