Java Convert GregorianCalendar to SQL Date

Tags: Java GregorianCalendar Java SQL Date

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

How to convert GregorianCalendar to SQL Date in Java

In Java, with a given GregorianCalendar object we can use follow the steps to convert it to a SQL Date object.

  • Step 1: using the GregorianCalendar.getTimeInMillis() method to return number of milliseconds since January 1, 1970, 00:00:00 GMT.
  • Step 2: using the java.sql.Date(long date) constructor to instantiate a new SQL Date object from milliseconds value of step 1.

ConvertGregorianCalendarToSQLDateExample1.java

import java.sql.Date;
import java.util.GregorianCalendar;

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

        // Convert GregorianCalendar object to SQL Date object
        Date date = new Date(gregorianCalendar.getTimeInMillis());

        System.out.println("GregorianCalendar: " + gregorianCalendar);
        System.out.println("SQL Date: " + date);
    }
}
The output as below.
GregorianCalendar: java.util.GregorianCalendar[time=1653285035223,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=23,DAY_OF_YEAR=143,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=0,HOUR_OF_DAY=12,MINUTE=50,SECOND=35,MILLISECOND=223,ZONE_OFFSET=25200000,DST_OFFSET=0]
SQL Date: 2022-05-23

Happy Coding 😊

Java Convert LocalDate to SQL Date

Java Convert Instant to SQL Date

Java Convert LocalDateTime to SQL Date

Java Convert ZonedDateTime to SQL Date

Java Convert OffsetDateTime to SQL Date

Java Convert Date to SQL Date

Java Convert Calendar to SQL Date

Java Convert SQL Date to LocalDate

Java Convert SQL Date to LocalDateTime

Java Convert SQL Date to ZonedDateTime

Java Convert SQL Date to OffsetDateTime

Java Convert SQL Date to Calendar

Java Convert SQL Date to GregorianCalendar

Java Convert SQL Date to Instant