tags:

views:

103

answers:

3

Currently I'm using TimeUnit.MILLISECONDS.toSeconds(valueInMillis) to check whether two millisecond values come from the same second. Can you recommend a faster algo for this operation?

Thanks.

+5  A: 

Divide each by 1000. Since they are integers/longs, the decimal will be truncated. If they are in the same seconds, the values will be the same.

phantombrain
... unless he needs to get rid of the rest of the date as well (from year down to minute), the question leaves room for interpretation ;)
Andreas_D
I need to check whether they are from the same year/month/date/hour/minute/second. ;)
paul_sns
If one doesn't care about the year/month/date, the upper values can be removed via modulus first
phantombrain
+3  A: 

This is the code behind TimeUnit.MILLISECONDS.toSecond(long d):

public long toSeconds(long d) { return d/(C3/C2); }

where C2,C3 are static constants. You can save a single division... In that case, I preferred your actual code, it's easier to understand

Andreas_D
If C2 and C3 are constants, the _compiler_ calculates the result of C3/C2 and uses that.
Thorbjørn Ravn Andersen
Even better ;) Then it's *as fast as possible*
Andreas_D
+1  A: 

Assuming t1 and t2 are time stamps. Eg from System.currentTimeMillis()

public static boolean isSameSecond(long t1, long t2){
  return (t1/1000) == (t2/1000)
}
Paul