Search code examples
javatimejava-timelocaltimeincompatibletypeerror

How can I convert sql time to java time for an object?


When i run this code it says this:

Error:(43, 31) java: incompatible types: java.sql.Time cannot be converted to java.time.LocalTime

public TrackTime read(int id){

        rs = jdbc.queryForRowSet("SELECT * FROM tracktime where id ='" + id + "'");
        while (rs.next()){
            return new TrackTime (rs.getInt("id"),
                    rs.getDate("date"),
                    rs.getTime("startTime"),
                    rs.getTime("endTime"),
                    rs.getString("licenseType"),
                    rs.getInt("trackNumber"));
        }

        return new TrackTime();
    }

what can be the cause of this error?


Solution

  • Your constructor for TrackTime class must be expecting object of class LocalTime where as rs.getTime("startTime") returns java.sql.Time instead of LocalTime and as both are not same hence you get the error.

    You can use toLocalTime() method on Time object which returns LocalTime object and this way correct object type would get passed to your constructor and should get away from the error.

    So in your code you need to do this,

    while (rs.next()){
        return new TrackTime (rs.getInt("id"),
                rs.getDate("date"),
                rs.getTime("startTime").toLocalTime(),
                rs.getTime("endTime").toLocalTime(),
                rs.getString("licenseType"),
                rs.getInt("trackNumber"));
    }