将时间戳舍入到最接近的10秒的最有效方法

Java (11) 中将给定时间戳(例如 System.currentTimeMillis())四舍五入到最接近 10 秒的最有效方法是什么?

例如 12:55:11 将是 12:55:10 而 12:55:16 将是 12:55:20

这段代码每秒执行约 10-20 次,因此它必须是高效的。

有任何想法吗?谢谢

回答

大概是这样的:

 long time = System.currentTimeMillis();
 long roundedTime = (time + 5_000) / 10_000 * 10_000;

基本上是 3 x 64 位原始算术运算。

(如果您想截断到 10 秒的粒度,只需删除+ 5_000.)

理论上我们应该考虑整数溢出。在实践中,上面的代码在接下来的大约 2.92 亿年里应该没问题。(来源:维基百科。)

  • if I run into issues after 292 million years, I'll contact you again. Thanks 😉
  • Remember we are doing Java integer division. That discards the fractional part so that the result is an integer. So dividing by 10_000 and multiplying by 10_000 truncates to 10 seconds. By adding 5_000 we are causing the computation to round rather than truncate. 14 seconds -> 10 and 15 seconds -> 20.

以上是将时间戳舍入到最接近的10秒的最有效方法的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>