java 时间戳间隔,Java如何在几秒钟内获得currentMillis和过去的时间戳之间的差异...

Lets say i have long currentMillis and long oldMillis. The difference between the two timestamps is very tiny and always less than 1 second.

If i want to know the difference between the timestamps in milleseconds, i can do the following:

long difference = currentmillis-oldmillis;

And if i want to convert difference to seconds, i can just divide it by 1000. However if the difference in milliseconds is less than 1000 milliseconds(<1 second), dividing it by 1000 will result in 0.

How can i get the difference between the two timestamps if the difference is less than a second? For example, if the difference is 500 milliseconds, the desired output is 0.5 seconds.

Using float/double instead of long always returns 0.0 for some reason i don't understand.

My code:

private long oldmillis = 0, difference = 0;

private long calculateDifference()

{

long currentMillis = System.currentTimeMillis();

if (oldMillis == 0) oldMillis = currentMillis;

difference = currentMillis - oldMillis;

oldMillis = currentMillis;

return difference;

}

The method calculateDifference is called randomly with a small random time interval.

解决方案

It sounds like you just need to convert the results into double before the division:

// This will work

double differenceMillis = currentMillis - oldMillis;

double differenceSeconds = differenceMillis / 1000;

// This will *not* work

double differenceSecondsBroken = (currentMillis - oldMillis) / 1000;

In the latter code, the division is performed using integer arithmetic, so you'll end up with a result of 0 that is then converted to a double.

An alternative which would work is to divide by 1000.0, which would force the arithmetic to be done using floating point:

double differenceSeconds = (currentMillis - oldMillis) / 1000.0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值