开发者

What's the most efficient way to check whether two long values (in millis) belong to the same second

Currently I'm using TimeUnit.MILLISECONDS.toSeconds(va开发者_JS百科lueInMillis) to check whether two millisecond values come from the same second. Can you recommend a faster algo for this operation?

Thanks.


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.


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


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜