Search code examples
javadatejdbcjava-8ucanaccess

Converting java.sql.Date values retrieved via JDBC into java.time.LocalDate?


I'm trying to retrieve date information from a Microsoft Access database using UCanAccess. I need to put it in a LocalDate column in a tableview and I'm doing this

Date date = res.getDate(3);
LocalDate dateEchantillonnage = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date) );

but it is causing me two problems:

The first one is that it gives a NullPointerException because sometimes the date can be null, so I want to know if there is a way to remedy to this.

The second one is when I replace

Date date = res.getDate(3);
LocalDate dateEchantillonnage = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date) );

with

Date date = new Date(2015-07-01);
LocalDate dateEchantillonnage = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date) );

it always displays the date as: 1970-01-01


Solution

  • Fix the NPE:

    Date date = res.getDate(3);
    LocalDate dateEchantillonnage = date == null
        ? null
        : LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date) );
    

    Fix the date always turning out to be 1970-01-01:

    Date date = Date.valueOf("2015-07-01"); // You passed an int 2015-07-01 = 2007 :)
    LocalDate dateEchantillonnage = date == null
        ? null
        : LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date) );