1

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

Gord Thompson
  • 98,607
  • 26
  • 164
  • 342
whites
  • 155
  • 1
  • 10

3 Answers3

1
Optional<LocalDate> dateEchantillonnage = date == null
    ? Optional.empty()
    : Optional.of(date.toLocalDate());
Joop Eggen
  • 96,344
  • 7
  • 73
  • 121
0

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) );
Lukas Eder
  • 181,694
  • 112
  • 597
  • 1,319
0

The following code works for me with UCanAccess 3.0.0 under JDK 1.8.0_51:

public static void main(String[] args) {
    String dbFilePath = "C:/Users/Public/UCanAccessDemo.accdb";
    String connUrl = "jdbc:ucanaccess://" + dbFilePath;
    try (Connection conn = DriverManager.getConnection(connUrl)) {
        String sql = "SELECT Date1 FROM DateTest ORDER BY ID";
        try (Statement st = conn.createStatement()) {
            try (ResultSet rs = st.executeQuery(sql)) {
                while (rs.next()) {
                    LocalDate dateEchantillonnage = null;
                    try {
                        dateEchantillonnage = rs.getDate(1).toLocalDate();
                    } catch (NullPointerException npe) {
                        // do nothing
                    }
                    System.out.println(dateEchantillonnage);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}
Gord Thompson
  • 98,607
  • 26
  • 164
  • 342