1

I've been comparing some fields and want to confirm my suspicion that although LocalDateTime fields might 'look' like the same values as converted timestamps, that they really don't hold the same values?

I'm writing a record using:

...
LocalDateTime ts = LocalDateTime.now();
pStmt.setTimestamp  (19,Timestamp.valueOf(ts));
pStmt.setTimestamp  (20,Timestamp.valueOf(ts));
a.createdt = ts;
a.lastupdt = ts;

and later I am reading that same DB record into another instance using:

...
b.createdt  = rs.getTimestamp("createdt").toLocalDateTime();
b.lastupdt  = rs.getTimestamp("lastupdt").toLocalDateTime();

When I check if a.createdt == b.createdt I get false. When I print the values as strings they look identical: "2016-03-21T23:40:38.700". Am I correct that the actual values held in memory for comparison are somehow different? e.g. the database probably holds more or fewer nanoseconds? Or that the conversion to timestamp and back does some truncation?

TIA

MaybeWeAreAllRobots
  • 1,105
  • 2
  • 9
  • 12
  • Objects, in general, must not be compared with ==, but with equals(). == is a reference comparison: it tests if two references point to the exact same object, not if two objects are functionally equal. – JB Nizet Mar 21 '16 at 13:10
  • Ah! I thought it was just a long field holding nanoseconds - that's how it has been described in most of my readings. But I see that you are right as it is described in the doco as an object. Note to self - whenever given an `equals` method, use it! Thanks. @JB Nizet - Post as an answer and I'll tick it. – MaybeWeAreAllRobots Mar 21 '16 at 13:55
  • All Objects have an equals() method. Objects should not be compared with ==, that's it. == is for primitives, and reference comparisons. – JB Nizet Mar 21 '16 at 14:32
  • As a side note: although what you have written probably works, a sql timestamp better maps with an OffsetDateTime or an Instant (depending on DB etc.) than with a LocalDateTime. – assylias Mar 21 '16 at 15:09

0 Answers0