0

I have the below code to get Current Timestamp and compute the Last Timestamp's elapsed time in minutes, am wondering if this can be optimized further for production

public static Timestamp getTimestamp() {
    java.util.Date date= new java.util.Date();       
    long time = date.getTime();          
    java.sql.Timestamp ts = new java.sql.Timestamp(time);
    return ts;
}

public static long getLastTimestampElapse(java.sql.Timestamp oldTime){
  long milliseconds1 = oldTime.getTime();
  long milliseconds2 = getTimestamp().getTime();
  long diff = milliseconds2 - milliseconds1;      
  long diffMinutes = diff / (60 * 1000);      
  return diffMinutes;
}
OTUser
  • 3,788
  • 19
  • 69
  • 127
  • You do you need the `Timestamp`? You can just use `System.currentTimeMillis()`. – marstran Mar 14 '19 at 18:21
  • For true elapsed time, do not use the milliseconds or current time. You need to use nano time. There is a lot of discussion on SO, but see [the answer on measurement](https://stackoverflow.com/questions/1770010/how-do-i-measure-time-elapsed-in-java). – KevinO Mar 14 '19 at 18:22
  • Possible duplicate of [How do I measure time elapsed in Java?](https://stackoverflow.com/questions/1770010/how-do-i-measure-time-elapsed-in-java) – KevinO Mar 14 '19 at 18:23

2 Answers2

1

From Java 8 upwards you can use the Duration class:

Timestamp timestamp = ...;
Duration duration = Duration.between(timestamp.toInstant(), Instant.now());
long diffMinutes = duration.toMinutes();
System.out.println(diffMinutes);
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
0

You can use stopwatch, details here: http://commons.apache.org/lang/

Package: org.apache.commons.lang.time.StopWatch

Mayank J
  • 71
  • 3