Java Convert LocalDateTime to SQL Date

Tags: Java LocalDateTime Java SQL Date Java 8

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

How to convert LocalDateTime to SQL Date in Java

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

  • Step 1: using the LocalDateTime.toLocalDate() method to convert the LocalDateTime object to LocalDate object.
  • Step 2: using the java.sql.Date.valueOf(LocalDate date) static method to instantiate a new SQL Date object from LocalDate value at step 1.

ConvertLocalDateTimeToSQLDateExample1.java

import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;

public class ConvertLocalDateTimeToSQLDateExample1 {
    public static void main(String... args) {
        LocalDateTime localDateTime = LocalDateTime.now();

        // Convert LocalDateTime object to SQL Date object
        LocalDate localDate = localDateTime.toLocalDate();
        Date date = Date.valueOf(localDate);

        System.out.println("LocalDateTime: " + localDateTime);
        System.out.println("Date: " + date);
    }
}
The output as below.
LocalDateTime: 2022-05-23T01:26:55.683395300
Date: 2022-05-23

Happy Coding 😊

Java Convert LocalDate to SQL Date

Java Convert Instant 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 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