Java Convert Calendar to SQL Date

Tags: Java Calendar Java SQL Date

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

How to convert Calendar to SQL Date in Java

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

  • Step 1: using the Calendar.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.

ConvertCalendarToSQLDateExample1.java

import java.sql.Date;
import java.util.Calendar;

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

        // Convert Calendar object to SQL Date object
        Date date = new Date(calendar.getTimeInMillis());

        System.out.println("Calendar: " + calendar);
        System.out.println("SQL Date: " + date);
    }
}
The output as below.
Calendar: java.util.GregorianCalendar[time=1653284907224,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=48,SECOND=27,MILLISECOND=224,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 GregorianCalendar 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