tl;dr
myResultSet.getObject( … , Instant.class )
.isBefore( Instant.now() )
Details
As has been discussed many times on Stack Overflow, you should:
- Store your date-time values in UTC.
- Never depend on the JVM’s current default time zone.
- Avoid the terrible legacy date-time classes such as
Date
, Calendar
, and the java.sql.* classes.
- Use only the java.time rather than the legacy date-time classes they supplant.
- Use a driver compliant with JDBC 4.2 or later to retrieve java.time objects.
- Avoid tracking time as a count-from-epoch, using objects instead.
I’m not an Oracle user, but it appears that DATE
is a legacy type, lacks any concept of time zone. I suggest using the standard TIMESTAMP WITH TIME ZONE
instead.
An Instant
is a moment on the timeline, always in UTC, with a resolution of nanoseconds.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Boolean isPast = instant.isBefore( Instant.now() ) ;
While I advise against tracking time as a count from epoch, if you insist, you can extract a count of milliseconds since the epoch of 1970-01-01T00:00:00Z. Beware of data loss as you are truncating any microseconds or nanoseconds that may be present.
long millis = instant.toEpochMilli() ;
About java.sql.Timestamp
, these objects are always in UTC. This confusing legacy class, badly designed as a hack, is now legacy and should be avoided. Replaced by java.time.Instant
.
The problem is the time-in-milli-seconds varies across the machines I'm running it on. For example, if the actual timestamp is 1511213580 ms, on machine1 this is 1511262180 ms and on machine2 it is 1511233380 ms.
That makes no sense as java.sql.Timestamp
will contain the same count from epoch in UTC across machines. I suspect the clocks of those alternate machines have been set to the wrong time, perhaps intentionally as a misguided attempt to handle time zone adjustment.
In that case you have a mess on your hands. The only workaround is to test each machine, calculate the delta between true UTC time and that particular machine’s incorrect clock. Then add or subtract that amount when obtaining data from that machine. Obviously risky as you never know when that confused sysadmin will attempt another adjustment hack.
The real solution is to: keep all servers in UTC and set to true accurate clock time, handle date-time values with java.time classes, and store moments in a column of type TIMESTAMP WITH TIME ZONE
.