3 Ways to Convert java.sql.date to/from Localdate in java: examples


java.sql.Date is an date class used to store date, time and timezone information.

LocalDate is stores Date only without time and timezone information This short tutorials talks about how to convert sql date to /from localdate in java with examples

How convert LocalDate to java.sql.date in java

LocalDate has valueOf method which convert to sql date

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

public class Main {

    public static void main(String[] args) {

        LocalDate localDate = LocalDate.of(2020, 07, 27);
        System.out.println(localDate); //2020-07-27
        Date sqlDate = Date.valueOf(localDate);
        System.out.println(sqlDate); //2020-07-27
    }
}

How to convert java.sql.Date to LocalDate

Multiple ways we can convert sql date to LocalDate

  • using toInstant() method

  • Create java.util.Date object to get current date

  • Converted currentDate to LocalDate using default zone with toInstant method.

Date currentDate = new Date(System.currentTimeMillis());
LocalDate current = currentDate.toInstant()
            .atZone(ZoneId.systemDefault()) 
            .toLocalDate();
  • toLocalDate method

java.sql.Date has toLocaleDate method which returns the LocalDate object.

It is an simple example

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

public class Main {

    public static void main(String[] args) {
        Date currentDate = new Date(System.currentTimeMillis());
        System.out.println(currentDate);
        LocalDate ld=currentDate.toLocalDate();
        System.out.println(ld);
    }
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.