Search code examples
javatomcatlocaldatetime

Java variable is Timestamp on one machine and LocalDateTime on another


I have a Java application, when I debug it on one machine, the type of a variable is LocalDateTime, but on another machine it is Timestamp.

This is the actual variable

Object teste = rs.getObject(i);

This is the LocalDateTime one, the Apache version is 7.0.106 and it is running with Windows Server 2019

Server version: Apache Tomcat/7.0.109
Server built:   Apr 22 2021 18:43:38 UTC
Server number:  7.0.109.0
OS Name:        Windows Server 2019
OS Version:     10.0
Architecture:   amd64
JVM Version:    1.8.0_291-b10
JVM Vendor:     Oracle Corporation

This is on the Timestamp one, the Apache version is 7.0.109 and it is running with Windows 10

Server version: Apache Tomcat/7.0.106
Server built:   Sep 16 2020 08:33:41 UTC
Server number:  7.0.106.0
OS Name:        Windows 10
OS Version:     10.0
Architecture:   amd64
JVM Version:    1.8.0_271-b09
JVM Vendor:     Oracle Corporation

I don't think it has something to do with the version, since it is just a patch, and reading the changelog there is nothing about it, I think it can be some configuration, but I can't find anything, if anyone could give me a guide or a place to look at, I would appreciate.


Solution

  • If your JDBC driver allows, specify that you want LocalDateTime each time:

    LocalDateTime teste = rs.getObject(i, LocalDateTime.class);
    

    LocalDateTime and other java.time classes are supported in this way since JDBC 4.2.

    Even better, assuming that your timestamp is just that, defining a point in time, use OffsetDateTime, not LocalDateTime. In most SQL databases you will then need to use timestamp with time zone.

    Alternatives for old JDBC drivers

    If specifying a java.time class to getObject() breaks, preferably upgrade your JDBC driver to one where it works. If for some reason you cannot do that, retrieve an old-fashioned Timestamp and convert it.

    LocalDateTime teste = rs.getTimestamp(i).toLocalDateTime();
    

    Or better for defining a point in time:

    Instant teste = rs.getTimestamp(i).toInstant();
    

    Why was the behaviour different?

    Probably you had different versions of your JDBC driver installed on those two computers. This can explain why one returns an old-fashioned Timestamp and the other a modern LocalDateTime. ResultSet and its methods including getObject are implemented in the driver.

    Link

    Arvind Kumar Avinash’s answer to Dates with no time or timezone component in Java/MySQL. It’s a different question, but that answer contains much good information that I think will be useful for you too.