2

I have two Timestamp objects, one for the current time and one for some time in the past. How can I calculate the amount of hours elapsed in between the two Timestamps?

java.sql.Timestamp currentTS = Timestamp(Calendar.getInstance().get(Calendar.MILLISECOND));
java.sql.Timestamp lastProcessedTS = Timestmp.valueOf(<some value in past>);
  • Do you want to calculate the duration in java or in SQL? In case you want to do it in Java and you have 1.8 try this: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html and that: https://docs.oracle.com/javase/tutorial/datetime/iso/period.html. Basically you can use long ns = Duration.between(t1, t2).toNanos() to get the difference in Nanos and the datetime-instant-conversion is explained here: http://stackoverflow.com/questions/19431234/converting-between-java-time-localdatetime-and-java-util-date. In case you want to use sql, please specify your DB/sql dialect. – Christian May 27 '16 at 21:38

2 Answers2

2
long elapsedTimeMillis = lastProcessedTS.getTime() - currentTS.getTime();
long hours = (elapsedTimeMillis / (1000 * 60 * 60)) % 24;
s7vr
  • 73,656
  • 11
  • 106
  • 127
0

java.time

Do not perform business logic on java.sql.Timestamp objects. That class is part of the legacy date-time classes bundled with the earliest versions of Java that have proven to be poorly designed, confusing, and troublesome. Avoid these classes where possible.

The java.time framework built into Java 8 and later supplants these old classes.

Much of the java.time functionality has been back-ported to Java 6 & 7 and further adapted for Android.

Instant

A java.time.Instant object represents a moment on the timeline in UTC with a resolution of nanoseconds.

If using a JDBC 4.2 driver, you may be able to call getObject to retrieve a SQL column of TIMESTAMP WITH TIME ZONE type directly into a Instant object.

If not able to get an Instant directly, get a java.sql.Timestamp and immediately convert to java.time. New methods added to the old classes facilitate conversions.

Instant instant = mySqlTimestamp.toInstant();

Duration

With a pair of Instant objects, define the elapsed span of time between them as a Duration.

Duration duration = Duration.between( start , stop );

Ask for the total number of hours in the entire span of time.

long totalHours = duration.toHours();

See this similar Question for more discussion.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154