# Getting the current timestamp and compute the timestamp difference in minutes

I have this code to get the current Timestamp and compute the last timestamp's difference with the current timestamp in minutes. I'm 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;
}


Note that none of these suggestions will have any significant impact on the performance of your application overall. Don't micro-optimize performance until you have known, tested bottlenecks.

The getTimestamp() method is noise. If all you care about is the current timestamp in milliseconds, use System.currentTimeMillis().

You can use a constant to store the number of milliseconds in a minute, potentially saving the multiplication. Even if the compiler optimizes the math away, it's easier to read.

A java.sql.Timestamp is a kind of java.util.Date, and the getTime() method is defined there. Your method should accept a java.util.Date to support more clients at no cost.

Your method is poorly named. Something like getMinutesSince() would be more readable. Likewise, there are better variable names than what you've selected.

Use final to indicate that variables won't be reassigned. That reduces the cognitive load on the reader.

You don't really need as many variables as you have. You might even be able to get away with none and still have a reasonably clear method.

If you were to use all my suggestions, your code might look more like:

private static final long MILLISECONDS_PER_MINUTE = 60 * 1000;

public static long getMinutesSince(final java.util.Date startTime) {
final long millisecondsSinceStart =
System.currentTimeMillis() - startTime.getTime();
return millisecondsSinceStart / MILLISECONDS_PER_MINUTE;
}

• You might want to assign MILLISECONDS_PER_MINUTE to something. :-) – AJNeufeld Mar 14 '19 at 23:51
• TimeUnit.MILLISECONDS.toMinutes(millisecondsSinceStart) - TimeUnit already has constants for you – Alexey Ragozin Mar 15 '19 at 3:33
• @AJNeufeld That's what I get for editing directly in the window instead of moving to my editor. Fixed, thanks! – Eric Stein Mar 15 '19 at 13:10
• @AlexeyRagozin That's a good point. I personally find it harder to read in this case, but it's a good option for the OP to be aware of. Thanks! – Eric Stein Mar 15 '19 at 13:11