Search code examples
javamysqllocaldate

Assign ("Months-days-hours") to a LocalDate variable


After a lot of tries I didn't found a way to assign a date taken from sql to a LocalDate variable in a pattern of ("MM-dd-hh"). I have defined a timestamp field(it goes from years to seconds) which I need to set a prenotation hour, day and month. What do you suggest?

public class Prenot {

    private LocalDate date;

    private Date datesql;

    public Prenot(LocalDate date) {

        this.date = date;
    }


    public LocalDate getDate() {
        return this.date;

    }

    public void setDate(LocalDate date) {
        this.date = date;
    }





    public static void visualizePrenot(Connection con,
            ObservableList<Prenot> list) {
        try {
            Connessione connn = new Connessione();
            FXMLDocumentController prova = new FXMLDocumentController();
            connn.estabilishConn(prova.getUser(), prova.getPass());
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM prenotazione");

            while (rs.next()) {

                list.add(new Prenot(
rs.getDate("data").toLocalDate());

            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }
}

edit: I focused the code to needs, Now what do you suggest, if I abandon the java.sql.Date, to get a TIMESTAMP value from a mysql db? And if so what do you think it's better to get, into another different getter, days and hours and show them in a TableView?


Solution

  • A LocalDate is a date without time of day (hours). You may think of it as year, month and day of month. If you need to store hours too, two options come to mind:

    • The standard solution is to store a timestamp in the database and use an Instant in Java. Then convert the Instant to ZonedDateTime when you need to display it to a user in some time zone.
    • Alternatively you may use a LocalDateTime in Java.

    In either case there is no need for a java.sql.Date or java.sql.Timestamp. With a sufficiently new JDBC driver (from Connector/J version 5.1.37 or so, I think) you can directly store a LocalDate, LocalDateTime, Instant or ZonedDateTime into the database and retrieve them as the same type again. If you really insist on using the outdated java.sql types, you need a Timestamp since a java.sql.Date doesn’t handle hour of day either.

    Disclaimer: It’s all something I’ve read, not something I have tried myself in practice.