Java Convert GregorianCalendar to Instant

Tags: Java GregorianCalendar Java Instant Java 8

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

How to convert GregorianCalendar to Instant in Java

In Java, with a given GregorianCalendar object we can use the GregorianCalendar.toInstant() method to convert it to an Instant object as the example Java code below.

ConvertGregorianCalendarToInstantExample1.java

import java.time.Instant;
import java.util.GregorianCalendar;

public class ConvertGregorianCalendarToInstantExample1 {
    public static void main(String... args) {
        GregorianCalendar gregorianCalendar = new GregorianCalendar();

        Instant instant = gregorianCalendar.toInstant();

        System.out.println("GregorianCalendar: " + gregorianCalendar);
        System.out.println("Instant: " + instant);
    }
}
The output as below.
GregorianCalendar: java.util.GregorianCalendar[time=1653220999302,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Bangkok",offset=25200000,dstSavings=0,useDaylight=false,transitions=3,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=4,WEEK_OF_YEAR=22,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=142,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=7,HOUR_OF_DAY=19,MINUTE=3,SECOND=19,MILLISECOND=302,ZONE_OFFSET=25200000,DST_OFFSET=0]
Instant: 2022-05-22T12:03:19.302Z

Happy Coding 😊

Java Convert GregorianCalendar to ZonedDateTime

Java Convert ZonedDateTime to GregorianCalendar